Boolean kotlin/java NullPointerException

I have a question about this code that combines Kotlin and Java. When I run the main method, it works well. However, when I run it in debug mode, I encounter a NullPointerException with it.adminRole but not with it.function. I need an explanation for this.

public class Role {

    public String function;

    public Boolean adminRole;

    public Role(){

    }
    public Role(String function, Boolean adminRole) {
        this.function = function;
        this.adminRole = adminRole;
    }

}
public class User {

    public String name;
    public String surname;

    public Role role;

    public User(){

    }
    public User(String name, String surname, Role role) {
        this.name = name;
        this.surname = surname;
        this.role = role;
    }
}
fun User.getUser(): TestUser? =
    this.role?.let {
        TestUser(
            adminRole = it.adminRole, //in debug mode i get NullPointerException( i want to understand why??)
            function = it.function, //in debug mode i get null value
        )
    }

fun main() {
    val user = User().apply {
        role = Role()
    }
    user.getUser()

}

data class TestUser(
    val adminRole: Boolean? = null,
    val function: String? = null,
)

Java object reference types, like Boolean, are initialized to null by default. If you wish it to have a non-null initial value you should say so in the constructor.

I’d try this:

public class Role {

    public final String function;

    public final Boolean adminRole;

    public Role() {
        this("", Boolean.False);
    }

    public Role(String function, Boolean adminRole) {
        this.function = function;
        this.adminRole = adminRole;
    }
}

It’s not recommended to make public variables mutable. I marked both as final to prevent modification after initialization.

I would also recommend that your default constructors call the full constructor with default values spelled out. It makes your intention clearer. It implies that you thought about your default constructor instead of allowing an IDE to auto generate it for you.

Leave a Comment