Nullable Types

Consider a method that can sometimes produce results that “have no meaning.” When this happens, the method doesn’t produce an error per se; nothing went wrong, there’s just “no answer.”

A good example is retrieving a value from a Map. If the Map doesn’t contain a value for a given key, it can’t give you an answer and returns a null reference to indicate “no value”:

// NullableTypes/NullInMaps.kt import atomictest.eq fun main(args: Array<String>) { val map = mapOf(0 to "yes", 1 to "no") map[2] eq null }

Languages like Java allow a result to be either null or a meaningful value. Unfortunately, if you treat null the same way you treat a meaningful value, you get a dramatic failure.1 The creator of the null reference, Tony Hoare, refers to it as “my billion-dollar mistake” (although it has arguably cost much more than that).

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.

  1. In Java, this produces a NullPointerException; in a more primitive language like C, a null pointer can crash the process or even the operating system or machine.