concept null reference in category kotlin

This is an excerpt from Manning's book The Joy of Kotlin.
At first, you may think that optional data might only be referenced with
var. What would be the point of creating a reference to an absence of data if not to eventually change this to a reference to some data? But how would you represent the absence of data? The most common way is to use what’s called a null reference. A null reference is a reference not pointing to anything, until some data is assigned to it.In this chapter, you’ll learn how to deal with optional data—absent values that aren’t the result of an error. I start by discussing problems with the null pointer. After that, I discuss how Kotlin handles null references and Kotlin’s alternatives to null references. For the remainder of the chapter, I describe how to create and use the
Optiontype as a solution for working with optional data. You can use theOptiontype to compose functions even when the data is absent.
Listing 6.2 Using
Optionto return a value from aMapimport com.fpinkotlin.optionaldata.exercise06.Option import com.fpinkotlin.optionaldata.exercise06.getOrElse data class Toon (val firstName: String, val lastName: String, val email: Option<String> = Option()) { companion object { operator fun invoke(firstName: String, lastName: String, email: String? = null) = Toon(firstName, lastName, Option(email)) } } fun <K, V> Map<K, V>.getOption(key: K) = Option(this[key]) #1 fun main(args: Array<String>) { val toons: Map<String, Toon> = mapOf( "Mickey" to Toon("Mickey", "Mouse", "mickey@disney.com"), "Minnie" to Toon("Minnie", "Mouse"), "Donald" to Toon("Donald", "Duck", "donald@disney.com")) val mickey = toons.getOption("Mickey").flatMap { it.email } #2 val minnie = toons.getOption("Minnie").flatMap { it.email } val goofy = toons.getOption("Goofy").flatMap { it.email } println(mickey.getOrElse { "No data" }) println(minnie.getOrElse { "No data" }) println(goofy.getOrElse { "No data" }) } #1 Extension function to implement the check-before-use pattern to avoid returning null references #2 Option composition through flatMap