Is there any way in kotlin to have constraints on a data classes values. I'm looking for something similar to the following java. It doesn't need to be an illegal argument exception, and the constraints aren't necessarily on String fields.
public class TotallyMadeUpClass{
private String username
public String getUsername(){ return this.username }
//Constrain the value somehow.
public void setUsername(String username) {
if (username.length > 10)
throw new IllegalArgumentException()
this.username = username}
}
Or this example which is even closer to what I'm trying to achieve.
public class TotallyMadeUpClass{
private final String username;
TotallyMadeUpClass(String username, OtherParams others){
if (username.length > 10)
throw new IllegalArgumentException()
this.username = username
}
public String getUsername(){ return this.username }
}
More idiomatic way to apply constrains in Kotlin is to use require function:
data class TotallyMadeUpClass(val username: String) {
init {
require(username.length > 10) { "Length must be greater than 10" }
// ...
}
}
It throws an IllegalArgumentException if the value is false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With