Handling Nulls In Kotlin

Kotlin offers us various options for handling nulls and in this post we’ll focus on the operators and the most common extensions that help us with that: safe call operator (?), assertion operator (!!) and the extension “let”.

Let’s take a look to the next code snippet:

var myVar: Int? = 42
// The operator ? indicates you are declaring a nullable type.
fun someMethod() {
if (myVar != null) {
println(myVar)
}
}

Well, you could say there’s nothing wrong with it, right?. That’s not true. The compiler will complain and will throw an error: Smart cast to ‘Int’ is impossible, because myVar is a mutable property that could have been changed by this time.

This error could be easily fixed by using the assertion operator (!!) since we already know that its value is not null

fun someMethod() {
if (myVar != null) {
println(myVar!!)
}
}
//Note: The assertion operator (!!) tells the compiler that myVar is not null.

… This is not quite right…

As the error description says, the value for myVar could have been changed to null (by some other function executed on any other thread…), and as a result you could get a NullPointerException (NPE) exception.

Kotlin gives us some ways to handle this situation.

One way of dealing with nulls is copying the value of myVar to a local variable and assign a default value to it in case myVar is null.

fun someMethod() {
val localCopy = myVar ?: 0
println
("Value: $localCopy")
}

Meet the ‘Elvis operator (?:)’.

This operator allows to check the value of ‘myVar’, if it’s not null it will be copied to 'localCopy’, else '0' will be assigned. This would be equivalent to:

// kotlin
val
copy = if (myVar != null) myVar else 0
// java
int copy = myVar != null ? myVar : 0

Piece of cake right?

Well, now, let me introduce you to ‘let’, a very useful extension.

fun someMethod() {
myVar?.let {
println(it)
}
}

In the example above you can see the use of ‘let’ as an extension of ‘myVar’. But, what does it do?

Well, in a general way to explain it, let unwraps the value of myVar? (be sure to use a safe call to avoid a NPE) and if it is not null it’s captured in an immutable value returned in the ‘it’ argument.

The ‘it’ argument can be renamed as you wish.

fun someMethod() {
myVar?.let { v ->
println(v)
}
}

//In this example 'it' was renamed to 'v'.

Until here we have seen how easy is to handle nulls, but, how do we do something else in a failure case?

The answer is we use another extension called ‘run:

fun someMethod() {
myVar?.let { value ->
println(value)
} ?: run {
println("Error")
}
}

In this example, when myVar is not null, we print its value, otherwise we print a message.

Great! so far you know some ways of handling nulls in Kotlin.

I hope you liked this post and you could learn something from it.