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)
}

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(String name) {
        this.name = name;
    }

}

It will give an error

Type mismatch.
Required: String
Found: String?
Clone this wiki locally