concept null reference in category kotlin

appears as: null references, A null reference, null reference
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Another common source of bugs is the null reference. As you’ll see in chapter 6, with Kotlin you can clearly separate code that allows null references from code that forbids these. But ultimately, it’s up to you to completely eradicate the use of null references from your programs.

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 Option type as a solution for working with optional data. You can use the Option type to compose functions even when the data is absent.

Listing 6.2 Using Option to return a value from a Map
import 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