I’ve been trying to do something with a model class in Kotlin that I’ve done many times before in Java, and I’ve been left without a clean way to do what I need.

Here’s what I’m trying to do in java:

import org.jetbrains.annotations.NotNull;

import java.util.UUID;

class User {

    @NotNull
    private final UUID userId;

    @NotNull
    private final String name;

    @NotNull
    private final String emailId;

    User(@NotNull final UUID userId, @NotNull final String name, @NotNull final String emailId) {
        this.userId = userId;
        this.name = name.trim();
        this.emailId = emailId.toLowerCase();
    }

    @NotNull
    UUID getUserId() {
        return userId;
    }

    @NotNull
    String getName() {
        return name;
    }

    @NotNull
    String getEmailId() {
        return emailId;
    }

}

The key things to note are the calls to name.trim(), and emailId.toLowerCase() in the constructor. These calls ensure that every User object created has a “valid” value for name and emailId.

Initially, in kotlin, this is what I had:

data class User(
    val userId: UUID,
    val name: String,
    val emailId: String
)

The problem here is that I don’t see any way of putting in the calls to trim() and toLowerCase().

Do you know of any ways to solve this problem? Please let me know: @gopalkri!

Gopal Sharma

gps gopalkri


Published