Nullable Types

The Billion-Dollar Mistake

In Java any object reference can be null. Calling a method on it crashes the app with a NullPointerException (NPE) — for years the most common Android crash. Kotlin fixes this in the type system:

  • String — can never hold null.
  • String? — a nullable type: can hold a string or null.
var name: String = "Asha"
name = null              // ERROR: Null can not be a value of a non-null type String

var nickname: String? = "Ash"
nickname = null          // OK
println(nickname.length) // ERROR: Only safe (?.) or non-null asserted (!!.) calls are allowed

Checking for null

Example

After an if (x != null) check, Kotlin smart casts the variable to the non-null type inside the block.

fun main() {
    val middleName: String? = null
    val city: String? = "Hyderabad"

    if (middleName != null) {
        println("Middle name length: ${middleName.length}")
    } else {
        println("No middle name")
    }

    if (city != null) {
        println("City has ${city.length} letters")   // smart cast to String
    }
}

Output

No middle name
City has 9 letters

Java vs Kotlin

JavaKotlin
Can a normal reference be null?yes, alwaysno
How to allow nullnothing to doadd ? to the type
When is the NPE found?at run time (crash)at compile time (error in the IDE)
Null checksif (x != null) everywhere?., ?:, let