Null Safety

Nullable types, ?., ?:, smart casts, let, and why !! should be rare.

In Kotlin, a String can never be null; a String? can. The compiler only lets you use a nullable value after you have handled the null case. This removes most NullPointerExceptions — the most common crash in Java and Android apps.

Handling null

s?.name returns null instead of crashing when s is null.

The Elvis operator ?: supplies a default when the left side is null.

After if (s != null), s is smart-cast to the non-null type.

?.let { ... } runs a block only for a non-null value.

toDoubleOrNull returns null for invalid text instead of throwing.

!! throws a NullPointerException when the value is null.

Java interop

val len = name!!.length val len = name?.length ?: 0 !! just moves the crash from compile time to run time. Use it only where null really is impossible and a crash would be the right outcome.

What does a?.b?.c ?: d evaluate to when a is null?

d: the safe calls short-circuit to null, and the Elvis operator replaces it with d.