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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.