Null Safety

Because Kotlin distinguishes between nullable and non-nullable types, the compiler is aware of the possibly dangerous situation of asking a variable defined as a nullable type to do something when the variable might not exist. To shield against these dangers, Kotlin will prevent you from calling functions on a value defined as nullable until you have accepted responsibility for this unsafe situation.

To see what this looks like in practice, try to call a function on beverage. This is a fancy tavern, and, as such, all drink names should be capitalized. Try to call capitalize on beverage. (You will see more String functions in Chapter 7.)

Listing 6.5  Using a nullable variable (Tavern.kt)

fun main(args: Array<String>) ...

Get Kotlin Programming: The Big Nerd Ranch Guide, First Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.