Twitter LogoFacebook Logo
Handling Null and NullPointExceptions
Eliminating the danger of null references
By: King

One major advantage in Kotlin is its Type System. It eliminates the the danger of having null references.

For example, if we declare and initialize a variable, it cannot be set to null anytime after.

var name: String = "John"

name = null 

In the above example, name = null will cause a compilation error.

Nullable References

To allow variables to accept null values, we use the "?" symbol after the type. 

var nane: String? = "John"

Now we can set the variable to null.

name = null

However, when we try to access a property of a nullable variable, it will not allow us to. We will get a compilation error. 

var numberOfCharactersInName = name.length

Handling Nullable References

To safely access a property of a nullable reference, we need to use the Safe Call operator (?).

var numberOfCharactersInName = name?.length

In the example, the Safe Call operator is placed before the Dot Operator to access the length property from the name variable.

This means that if name is equal to null, it will return null, otherwise it will return the value of name.length.

Another way we can safely access a property of a nullable reference is to check if the reference is not null using a If Statement.

if(name != null) {

   var numberOfCharactersInName = name.length


var numberOfCharactersInName = if(name != null) name.length else 0

Elvis Operator

The Elvis Operator is similar to an If Statement.


[expression] ?: [value_to_return_if_null] 

Instead of using the full If statement - if(name != null) ... else ... - we can shorten the code with the Elvis Operator.

var numberOfCharactersInName = name?.length?: 20;

If the expression on the left of the (?:) is not null, it will return that value, otherwise, it will return the value on the right.

In this example, since name = "John," it is not null. Thus, it will return 4. If name was null, it will return 20.

Not-Null Assertion Operator (!!)

The Not-Null Assertion Operator (!!) forces the compiler to ignore its checks on the reference to check whether the value is null or not.

The (!!) operator will turn any reference into a non-null type and it will throw an NullPointerException if the value is null. 

var numberOfCharactersInName = name!!.length;

If name = null, it will throw an error.

Sign In