Null Pointer Exception handling in Kotlin

Panduka Wedisinghe
2 min readAug 2, 2018

Null Pointer Exception aka NPE is a Billion Dollar question for the developers around the world never mind the language they are using for the development. Revolutionary Kotlin offers certain ways to handle this bummer exception. In this article I’m going to discuss these methods of avoiding NPE with suitable illustrations.

Kotlin’s Type System eliminates the NPE from our source code despite the fact that still there are certain possibilities where NPE may encounter.

  1. An explicit call to throw NullPointerException
  2. Usage of the !! operator (will be discussed)
  3. Some data inconsistency with regard to initialization
  4. Java Interpolation

How to avoid NPE ?

  1. A reference must be explicitly marked as nullable when null value is possible
var a: String? = "Friend"
a = null //allowed as a is marked as nullable with ?

But still we are at a risk. What if we called any possible method on a ? Fortunately Kotlin is smart enough to stop us doing such a mistake. Let me show you what happens if we do this by mistake…

An error pops up and some options are suggested by the IDE. Now its time to go deep and study what these options are and how they work. Lets dive deeper.

Surrounding with Null Check

if (a != null) {
println("a length:${a.length}")
}

More conventional way of doing the job is checkin null before we use the reference.

Safe Calls(?. operator)

Safe calls is a method of checking if a reference is null. An example is shown below

println("a length:${a?.length}")

Safe calls are more useful in chains. For example, lets say Jon is a developer assigned to a project(or not) and needs to get project manager’s name

jon?.project?.manager?.name

Elvis Operator(?:)

Elvis operator is more like an if else statement. If a is not null do this else do this

println("Length a: ${a?.length ?: "a is null"}")val l = a?.length ?: -1

Not- null assertion operator (!!)

!! operator converts any value to non-null type and if the value is null trows an exception. If you want an NPE, you need to ask for it explicitly. It does not happen randomly like in any other languages.

try {
println("a...... length:${a!!.length}")
} catch (e: NullPointerException){
println("a is null")
}

I hope this article is useful to those who learn Kotlin and try using it in their coding environments. I hope to see you with another useful topic sometime soon.

--

--

Panduka Wedisinghe

Android Developer /Software Engineer/Flutter Developer