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?
Optional? Do you really need to distinguish two different kinds of missing value (nullandOptional.empty())? —Optionaldoesn'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.