Understanding Null Safety in Kotlin

jbc7ag

Jess Barrientos

Posted on July 17, 2020

Understanding Null Safety in Kotlin

Programming errors involving nulls have been the source of countless bugs.


Kotlin is fighting NullPointerException (NPE) by introducing non-nullable and nullable variables, and now we can distinguish between references that can contain null values and those that cannot, and it is done natively.

By default, variables cannot contain nulls. BUT we can indicate that a variable can contain them using just a question mark (?). Take a look at the next example:

var dinosaur: String = null
// error: null can not be a value of a non-null type String

val dinosaur: String? = null // That’s better
print(dinosaur)
//output -> null
Enter fullscreen mode Exit fullscreen mode

Easy peasy ... It's important to know some operators that can help us evaluate these null assignments.

? Operator (Safe calls)

This operator helps us to evaluate a variable that was previously defined as a variable that can hold nulls like in the next example:

val dinosaur: String? = null

print(dinosaur?.length)
// output-> null
Enter fullscreen mode Exit fullscreen mode

We can also do the same with a non-nullable variable but this is an unnecessary safe call:

val dinosaur: String = "I'm a dinosaur"
print(dinosaur?.length)
//output -> 14
Enter fullscreen mode Exit fullscreen mode

This is another example of using it with data classes, for example:

// we define that isSpacy can hold nulls
data class Taco(var name: String, var isSpacy: Boolean?)
Enter fullscreen mode Exit fullscreen mode

Then we can do something like this:

// here we set isSapacy as null
val myTaco = Taco("Pastor", null) 
Enter fullscreen mode Exit fullscreen mode

So we have myTaco with isSpacy as null so the next code won’t compile:

myTaco.isSpacy.equals ("false”)
// error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Boolean?
Enter fullscreen mode Exit fullscreen mode

Instead of that, we should do a safe call like this:

myTaco.isSpacy?.equals(false)
//output -> null
Enter fullscreen mode Exit fullscreen mode

In the previous example, Kotlin will evaluate myTaco.isSpacy and if it's null it will return null, else it will continue the execution of the code.

The ?: Operator or Elvis Operator

This Kotlin operator is a simple “if” that help us to easily and clear check if a value is null.

So this odd code:

val fruitName: String? = null

val nameLength: Int = if (fruitName! = null) fruitName.length else -1
Enter fullscreen mode Exit fullscreen mode

Can be written like this:

val nameLength: Int = fruitName?.length ?: -1
Enter fullscreen mode Exit fullscreen mode

If fruitName is null then return -1 else return whatever fruitName.length is.

The !! Operator, Bang Bang operator or double-bang operator

So far, so good, but what happens if I really like NullPointerExceptions. Where are they? In this case, Kotlin let up to us manage the NPE. So, here is where we can use the bang-bang operator (!!)

Remainder: This is only for NPE-lovers

val size = fruitName!!.length
Enter fullscreen mode Exit fullscreen mode

Here we are telling Kotlin that we want to get an NPE in case of fruitName has a null value, So we are asking for an NPE explicitly and it is well known that if we can, avoid this operator.


As we saw, Kotlin provides us an easy option to handle the pain of getting NullPointerExceptions, and almost always it does not allow us to compile our code until we fix them. So now, let's avoid them wisely.

💖 💪 🙅 🚩
jbc7ag
Jess Barrientos

Posted on July 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related