How to remove all !! from your Kotlin code

Null safety is one of the best features of Kotlin. It makes you think about nullability on the language level so you can avoid many hidden NullPointerExceptions which are so common in Java. However, when you automatically convert your Java code into Kotlin, you can see a lot of !! symbols there. It looks like you should not have any !! in your code unless it’s a quick prototype. And I believe it’s true, because !! basically means “you have a potentially unhandled KotlinNullPointerException here”. Plus it looks hacky.

Kotlin has some clever mechanisms how to avoid this, but figuring them out is not straightforward. Here are 6 ways how to do that:

1) Use val instead of var

2) Use lateinit

It lets you replace this:

With this:

Be aware, that accessing non-initialized lateinit property will result in UninitializedPropertyAccessException.

lateinit sadly doesn’t work with primitive data types like Int. For primitive types you can use delegates like this:

private var mNumber: Int by Delegates.notNull<Int>()

3) Use let function

It annoyed me: I know that that this mutable property couldn’t have been changed after the null check. And many developers quick-fix it with:

But there is an elegant solution using let function:

4) Create global functions to handle more complex cases

You could nest two let calls, but that wouldn’t be very readable. In Kotlin, you can have globally accessible functions so you can easily build a function you need which is used like this:

Code of this function:

5) Use Elvis operator

With this:

6) Crash on your own terms

Replace this:

With this:

Conclusion

Google Developer Expert for Android, Founder & CEO at Step Up Labs, early adopter.