Skip to content

Using @Nullable and @NotNull in kotlin

Devrath edited this page Jan 27, 2024 · 3 revisions

key

Scenario: Where there can cause an exception

Observation

  • Note since the name variable is not initialized and is accessed in kotlin.
  • Since kotlin explicitly does not check the null and kotlin compiler does not know it can be nullable.

Consider the Java code

public class SuperHero {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Consider accessing in kotlin

fun nullableNotNull() {
        val superHero = SuperHero()
        val heroName : String? = superHero.name
        println(heroName)
        //superHero.setName(null)
}

Output

FATAL EXCEPTION: main
Process: com.istudio.app, PID: 13088
java.lang.NullPointerException: getName(...) must not be null

Solution

public class SuperHero {

    private String name;

    public @Nullable String getName() {
        return name;
    }

    public void setName(@NotNull String name) {
        this.name = name;
    }

}

Accessing a null will point to the error

Type mismatch.
Required: String
Found: String?

Setting the null value

Null can not be a value of a non-null type String
Clone this wiki locally