Learning Android Kotlin

7 ways to null crash Android Kotlin without using !!

Thought there won’t be null crashes if you are not using !! on Kotlin?

Photo by Ivan Vranić on Unsplash

One of the nice bit of Kotlin compared to Java is its ability to handle nullability. If we have a possible null code, Android Studio will error out during compile time. It is indicated clearly as shown below.

It seems like the only way to null crash during runtime in Kotlin is to use !! explicitly.

However, listed below are 7 possible ways that will crash your due to null (or something of that nature 😉) without using !! at all.

1. Getting value from Intent in Android

If you are using Android API 29 or earlier, you can get your String from the Intent as below

val value: String = intent.getStringExtra("MY_KEY")

There won’t be any error and you can compile the code. However, if the intent doesn’t store anything using MY_KEY, then it will null crash 💥.

Solution

You can just check for null.

val value: String = intent.getStringExtra("MY_KEY") ?: ""

--

--