Null Safety in Kotlin

The definitive guide to handling null references in Kotlin

Anirban Chatterjee
The Startup
5 min readJun 30, 2020

--

Overview

In this article, we’ll look into the null safety in Kotlin.

Any programming language which has the concept of null reference throws a NullPointerException. It has been referred to as a billion-dollar mistake. (Wiki)

Nullable and Non-Nullable Type

Kotlin aims at eliminating the risk of NullPointerException. It distinguishes between nullable and non-nullable references as a part of its type system.

In Kotlin, all variables are non-nullable by default. We cannot assign a null value to a variable because it’ll throw a compilation error:

To define a nullable variable, we must append a question mark(?) to the type declaration:

We can call a method or access a property on a non-nullable variable. However, in the case of nullable variables, we need to handle the null case explicitly. Otherwise, it will throw a compilation error since Kotlin knows that the variable contains null references:

Let’s look at the different ways how we can handle null references safely in Kotlin.

Working With Nullable Types

Null Check

We can use the if-else expression to explicitly check for nullable variables. This option works only where the variable is immutable. Depending on the complexity of the conditions, this can also lead to nested expressions.

Let’s look at an example:

Safe Call Operator ( ?. )

Kotlin has a safe call operator(?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.

Let’s see how to use a safe call operator:

We can also use the safe call operator for multiple chain calls:

The chain calls return null if any of the properties are null:

Using let() Method

We can use the let() method along with the safe call operator to act on a non-nullable variable:

Using also() Method

We can use the also() method to execute additional operations like logging and printing of the non-nullable variables. This method can be used in a chain with let() or run() method.

Here's how we can use also() method along with let() method:

Using run() Method

We can use the run() method to execute some operations on a non-nullable reference. This method operates using this reference and returns the value of the lambda result:

Elvis Operator ( ?: )

We can use the Elvis operator(?:) to return a default value only if the original variable has a null value. If the left-side expression of the Elvis operator has a non-nullable value, then it is returned. Otherwise, the right-side expression is returned.

Let’s take a look at how the Elvis operator works:

We can use the Elvis operator with a safe call operator to invoke a method or property of the variable:

We can also use throw and return expression in the right-side expression of the Elvis operator. So instead of default values, we can throw specific exceptions in the right-side expressions of the Elvis operator:

Not Null Assertion Operator ( !! )

We can use the not-null assertion operator(!!) to explicitly throw a NullPointerException. This operator converts any reference to its non-nullable type and throws an exception if the reference has a null value.

Let’s have a look into how we can throw NullPointerException using not-null assertion operator(!!):

However, if the reference has a non-nullable value, then it is executed successfully:

The not-null assertion operator should be used carefully since it’s a potential sign of a NullPointerException. We should avoid using multiple non-null assertions like the following since it makes it harder to debug which property is null:

We should always try to use safe call operator in such cases to ensure NullPointerException doesn’t occur:

Nullability in Collections

Kotlin collections are non-nullable by default. To define a collection of nullable types in Kotlin, we have to append question mark(?) to the type declaration:

We can use the following way to define a nullable collection in Kotlin:

Filtering Nullable Types

We can filter a list that contains nullable values to return only the non-nullable values using the filterNotNull() method.

Let’s have a look at an example:

Conclusion

In this article, we look into the various ways to handle nullable references in Kotlin.

The code for these examples is available on GitHub.

Originally published on Anirban’s Tech Blog

--

--

Anirban Chatterjee
The Startup

Software Engineer | Blogger | Traveler | Football fan | Amateur Photographer