Null safety

Kotlin supports a more strict type system when compared to Java, and divides all types into two groups, as follows:

  • Nullable
  • No-nullable

One of the most popular causes of an app crashing is the NullPointerException. This happens as a result of accessing a member of a null reference. Kotlin provides a mechanism that helps us to avoid this error by using a type system.

The following diagram shows what the class hierarchy looks like in Kotlin:

In Kotlin, nullable types have the same names as no-nullable types, except with the ? character at the end.

If we use a no-nullable variable, we can't assign null to it, and the following code can't be compiled:

var name = "Igor"
name = null

To be able to compile this code, we have to explicitly declare the name variable as nullable:

var name: String? = "Igor"
name = null

After doing this, we cannot compile the following code:

name.length

To access members of nullable types, we have to use the ?. operator, like in the following example:

name?.length

One expression can contain the ?. operator as many times as needed:

name?.length?.compareTo(4)

If a member in this chain is null, the next member can't be invoked.

To provide an alternative program flow, if null is encountered, we can use the Elvis operator (?:). This can be used in the following way:

name?.length?.compareTo(4) ?: { println("name is null") }()

The preceding snippet demonstrates that the Elvis operator can be used if we want invoke a block of code if an expression returns as null.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.240.119