7 Working with nullable values

 

This chapter covers

  • Nullable types
  • Syntax for dealing with values that are potentially null
  • Converting between nullable and non-nullable types
  • Interoperability between Kotlin’s concept of nullability and Java code

By now, you’ve seen a large part of Kotlin’s syntax in action. You’ve moved beyond creating basic code in Kotlin and are ready to enjoy some of Kotlin’s productivity features that can make your code more compact and readable. One of the essential features in Kotlin that helps improve the reliability of your code is its support for nullable types. Let’s look at the details.

7.1 Avoiding NullPointerExceptions and handling the absence of values: Nullability

Nullability is a feature of the Kotlin type system that helps you avoid NullPointerException (NPE) errors. As a user of a program, you’ve probably seen an error message similar to “An error has occurred: java.lang.NullPointerException,” with no additional details. On Android, you may have seen another version of this message, along the lines of “Unfortunately, application X has stopped,” which often also conceals a NullPointerException as a cause. Such errors occurring at run time are troublesome for both users and developers.

7.2 Making possibly null variables explicit with nullable types

7.3 Taking a closer look at the meaning of types

7.4 Combining null checks and method calls with the safe call operator: ?.

7.5 Providing default values in null cases with the Elvis operator: ?:

7.6 Safely casting values without throwing exceptions: as?

7.7 Making promises to the compiler with the non-null assertion operator: !!

7.8 Dealing with nullable expressions: The let function

7.9 Non-null types without immediate initialization: Late-initialized properties

7.10 Extending types without the safe-call operator: Extensions for nullable types

7.11 Nullability of type parameters

7.12 Nullability and Java

7.12.1 Platform types

7.12.2 Inheritance