Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Data Class enforce value constraints

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 }


}
like image 561
Wes Avatar asked Mar 18 '26 19:03

Wes


1 Answers

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.

like image 126
Sergey Avatar answered Mar 21 '26 09:03

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!