Codementor Events

The different ways to handle Nullable type in Kotlin

Published Dec 14, 2018Last updated Jun 11, 2019

Original Post available at Medium

We all know how Kotlin handles the “Billion Dollar Mistake” present in Java, improving the way we handle Null Pointer Exceptions (NPE). While exploring different possible ways to handle the NPE effectively I read various blog posts and Kotlin documentation. To my surprise, many of the Android Developers think either Koltin has removed the NPE or it handles it on its own. What exactly Kotlin says is ‘ Nulls in Kotlin don’t exist until you say’, that is no variable by default is null.

We just differentiate between Null and Non-Null object types in Kotlin and have to explicitly handle it as we used to do with a variable in Java.

Kotlin by default forces to initialize every object with a value and that should not be null.
var showButton: Button = null // Compile Time Error

However, we can make a nullable type object, by explicitly informing Kotlin that the object can be null.
var showButton: Button? = null // No Compile Time Error

When using a nullable type, the Secure Access Operation ?. or Not Null Assertion !! operators have to be used to access the nullable variable.

In this case, if x is null, then the expression will return null as well. So y will be of type Double? . There might be cases when you know that your object cannot be null, then we use Not Null Operator !! to assert that object is not null for sure and hence avoiding the null check. (I suggest to use this rarely since if you are using this operator you are actually doing the same things as we used to do in Java)

The not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null. We can write x!!, and this will return a non-null value of x or throw an NPE if x is null.

Kotlin’s requireNotNull() vs Not Null Assertion !!

Kotlin provides two methods to call nullable type objects — requireNotNull() and !! operator. Both throws an exception if the object is null. When I came across these two methods, I was curious to know what’s the difference between the two ways. Here is what I got to know:
x!!throws a Null Pointer Exception if x is a null object and requireNotNull(x) throws IllegalArguementException if x null.
Also, Objects.requireNotNull() is available with Java in Android, however only with the recent API versions. Using each of these in a correct place helps in debugging the code in a better way.


Follow me on Twitter , Facebook or LinkedIn , will post an update when I write new posts.

Discover and read more posts from Yashish Dua
get started
post commentsBe the first to share your opinion
Show more replies