The Billion-Dollar Mistake

The Billion-Dollar Mistake and How Kotlin Avoids It

Tony Hoare added the null reference to ALGOL W in 1965 and in 2009 called it "my billion-dollar mistake", made "simply because it was so easy to implement". In JavaScript, a property access on the undefined that find() returns fails on the user's phone; in Java it is the NullPointerException, a crash the Google Home team cut by 30% by moving to Kotlin.

Kotlin moves the check to compile time by splitting every type in two: String never holds null, String? may. Assigning null to the first is an error, and so is calling a member of the second unchecked:

nonull.kt: two null mistakes the compiler rejectsKotlin
fun main() {
    var title: String = "The Quiet Harbor"
    title = null
    val found = listOf("The Quiet Harbor").find { it.startsWith("Salt") }  // String?
    println(found.length)
}
Output
nonull.kt:3:13: error: null cannot be a value of a non-null type 'String'.
...
nonull.kt:5:18: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a
  nullable receiver of type 'String?'.
...

String? is no wrapper like Java's Optional, just a reference the compiler tracks. Every T is a subtype of T?, so a non-null value fits wherever a nullable one is expected, never the reverse:

Every non-null type is a subtype of its nullable twin; Any? sits at the top
Every non-null type is a subtype of its nullable twin; Any? sits at the top