Null Safety (Kotlin)

Null safety is Kotlin's type-system feature that distinguishes nullable types (String?) from non-nullable ones (String), eliminating most NullPointerExceptions at compile time.

Kotlin

In Kotlin a regular type can never hold null. To allow null you append ?, making the type nullable (String?). The compiler then forces you to handle the null case before you can dereference the value, turning runtime NullPointerExceptions into compile-time errors.

You work with nullable values using the safe-call operator ?. (returns null instead of crashing), the Elvis operator ?: (supply a default), and—when you're certain it isn't null—the not-null assertion !! (which throws if you're wrong). Smart casts also let the compiler treat a value as non-null after you check it.

This single design decision is one of Kotlin's headline advantages over Java. The goal is to make the 'billion-dollar mistake' of null references explicit and safe rather than lurking everywhere.

Syntax

var name: String = "Ana"   // never null
var nick: String? = null   // nullable

Examples

Kotlin

fun greet(name: String?) {
    val len = name?.length ?: 0
    println("length is $len")
}
greet("hi")
greet(null)

Output:

length is 2
length is 0

Learn it in a lesson

See also

Back to the Dictionary