From Junior to Master in Kotlin — 2 (Safe null)

Gerardo Lopez Falcón
May 26 · 3 min read

Kotlin by default does not allow null initializations unless you tell it otherwise. Personally, I love that Kotlin “hates” nulls, it forces me to initialize and implement proper strategies to handle nulls if we have to.

One of the most common mistakes in many programming languages is when we try to access a member of a null reference, which will result in a null pointer exception or NPE for short.

Let me show you how to declare a variable not null and how Kotlin throws an error when I assign a null to the variable:

You run the code:

So good, a compilation error comes in. To be honest, I prefer this kind of error instead of runtime exceptions, when the app is running and crashes due to NPE it seems that the app wasn’t developed carefully (my opinion).

If you need that you code allows nulls (You are weird but we love you :D, it is a joke) you could do the following:

var name: String? = “Gerardo” // can be set null
print(name) //Prints Gerardo

But if you want to access the same property on `name`, that wouldn’t be safe, and the compiler reports an error:

val length = name.length // error: variable ‘name’ could be null

But what if you need to access properties or methods of your variables that could be null? There are a few ways of doing that.

Safe calls

The safe call operator is ? . See the following example:

val name= "Gerardo"
val lastName: String? = null
println(name?.length) // Unnecessary safe call
println(lastName?.length)

The safe operator first checks if the value isn’t null so allows the execution, otherwirse returns a null. Bye bye Null pointers exceptions… You were History. So about the example, the compiler will return a null when the lastName variable tries to access length property and won’t throw an error. Yessss, saaaafeeeee cooodeeeee.

The !! operator

Kotlin respects all developers decisions, good or bad, but repects all. So, if you for some reason love the NPE, Kotlin allows it, but I would like very good why I need a NPE… If you want to allow NPE, use !!

val lastNameTemp= lastName!!.length

If lastName is null then a ungly NPE will be thrown.

Elvis operator

Another option could be use the elvis operator ?: as following:

val l = lastName?.length ?: "Falcon"

If the expression to the left of ?: is not null, the operator returns it, otherwise will use the default value that you chose, in this context it is “Falcon”. No bad.

Conclusion

Enough info by today. In other posts I will talk about other advanced choices such as lazy loading and lateinit… Thank you for following me and sharing it with your friends.

Long Live Kotlin.

Google Developers Experts

Experts on various Google products talking tech.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store