0

I have the following Java class in my project

public class Post {

    public final @Nullable Optional<@Size(min = 10, max = 255) String> title;

    public Post(@JsonProperty("title") @Nullable Optional<String> title) {
        this.title = title;
    }
}

This class, when used with the @Valid annotation in a RestController, allows for null values and String values with 10 to 255 characters.

I want to replicate the same behavior in Kotlin. What I came up with was the following:

class Post(
  @JsonProperty("title") 
  val title: Optional<@Size(min = 10, max = 255) String>?
)

However, this class no longer enforces the @Size constraint and allows String values of any length.

How can I fix this and make it enforce the @Size constraint properly?

2
  • 1
    A nullable Optional? Do you really need to distinguish two different kinds of missing value (null and Optional.empty())? — Optional doesn't tend to be used in Kotlin; in Java it improves null safety a little, but Kotlin doesn't need its syntactic and performance overheads, because Kotlin already has null-safety baked into its type system and syntax. Commented Sep 19, 2022 at 19:44
  • Yes, I am using it to differentiate between when a user submits a request body with the property set to null vs when they submit a request body with the property not present. Do you think there is a better way to achieve the same goal? Either way, this doesn't apply only to Optionals and is present across all generic types, I assume Commented Sep 19, 2022 at 19:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.