KtKotlin
IntermediateLesson 7 of 16

Null Safety – Kotlin

Nullable types, safe call, Elvis, smart cast, and !!.

In Kotlin, a normal variable can never be null. Only types with a question mark (String?) allow null. The compiler forces you to handle it safely – so NullPointerException is largely a thing of the past.

fun laenge(text: String?): Int = text?.length ?: 0

fun main() {
    println(laenge("Kotlin"))     // 6
    println(laenge(null))         // 0
}
// var s: String = null          // compile error

The most important tools: the safe call ?. (returns null if the left side is null), Elvis ?: (fallback value for null), smart cast (after a check, the type is automatically non-null), and let for a block that runs only for non-null values.

fun zeige(x: String?) {
    if (x != null) {
        println(x.uppercase())            // smart cast: x is a String here
    }
    x?.let { println("Length: ${it.length}") }
    println(x?.trim()?.length)            // chains are possible
    val n = x ?: return                   // exit early
    println("not null: $n")
}
zeige("  Ada ")
zeige(null)

The not-null assertion operator !! throws a NullPointerException if the value turns out to be null – avoid it whenever possible. The cast with as? is safe, and you remove null from lists with filterNotNull.

val wert: Any = 42
val text: String? = wert as? String        // null instead of ClassCastException
println(text)                              // null

println(listOf("a", null, "b").filterNotNull())   // [a, b]
println("12".toIntOrNull() ?: 0)           // 12

lateinit var spaeter: String               // set only later (var only, objects only)
fun pruefe(x: Int?) {
    val sicher = requireNotNull(x) { "x must not be null" }
    println(sicher + 1)
}
WarningFor Java calls, return types are "platform types" (String!): the compiler cannot know whether null is possible. Check such values yourself, otherwise you may still get an NPE.
TipPrefer ?. and ?: over !!. Instead of if (x != null) x.foo() you write x?.foo().