Null Safety - The Billion Dollar Fix

Article · 2:00

How making absence part of the type removes the most common crash in Android.

Tony Hoare, who invented the null reference in 1965, later called it his billion-dollar mistake. The problem is not that absence exists - plenty of things legitimately have no value - but that in most languages a variable of type String might hold a string or might hold nothing, and only one of those supports calling a method.

Kotlin splits them. String holds a string, always. String? holds a string or null. They are different types, and the compiler will not let you call a method on the second without first establishing which case you are in. Since the vast majority of values in a real program are never null, the vast majority of declarations carry no extra syntax at all.

Three operators do nearly all the work:

  • ?. calls the method only if the receiver is non-null, giving null otherwise.
  • ?: the elvis operator, supplies a fallback when the left side is null.
  • !! asserts non-null and throws if wrong. Treat every use as a question to answer later.

There is also smart casting. After you check a nullable value against null, the compiler knows it is not null for the rest of that branch and lets you use it directly, with no cast and no second check.

fun describe(name: String?): String {
    // ?. gives null instead of crashing; ?: supplies the fallback
    val length = name?.length ?: 0

    // After this check the compiler smart-casts name to String
    if (name != null) {
        println("Inside the branch, ${name.uppercase()} needs no ?.")
    }

    return "Name has $length characters"
}

fun main() {
    println(describe("Kotlin"))   // Name has 6 characters
    println(describe(null))       // Name has 0 characters
}

Discussion

No questions on this topic yet. Sign in to ask the first one.