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?

  • 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. – gidds Sep 19 '22 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 – André Lima Sep 19 '22 at 19:48

0 Answers0