Null safety

Kotlin has amazing stuff to work with null references. The null reference is a nightmare for Java developers. The Java 8 has an Optional object, which helps developers work with nullable objects, but is not concise like in Kotlin.

Now, we will explore how Kotlin can help developers to avoid the NullPointerException. Let's understand.

The Kotlin type system makes a distinction between references which can hold null and those which cannot hold null. Due to this, the code is more concise and readable because it is a kind of advice for developers.

When the reference does not allow null, the declaration should be:

var myNonNullString:String = "my non null string"

The preceding variable cannot be assigned to a null reference, if we ...

Get Spring 5.0 By Example 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.