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
Kotlin makes you think about immutability on the language level and that’s great.
val is read-only,
var mutable. It’s recommended to use as many read-only properties as you can. They are thread-safe and work great with functional programming. If you use them as immutables, you don’t have to care about nullability. Just beware that
val can actually be mutable.
2) Use lateinit
Sometimes you can’t use immutable properties. For example, it happens on Android when some property is initialized in
onCreate() call. For these situations, Kotlin has a language feature called
It lets you replace this:
Be aware, that accessing non-initialized
lateinit property will result in
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
This is a common compile-time error in Kotlin code:
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
4) Create global functions to handle more complex cases
let is a great replacement for a simple null check, but there might be more complex cases. For example:
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
Elvis operator is great when you have a fallback value for the null case. So you can replace this:
6) Crash on your own terms
There are still cases when you know something can’t be null, even though the type must be nullable. If it’s null, it’s a bug in the code and you should know about it. However, leaving
!! there gives you a generic
KotlinNullPointerException which is hard to debug. Use build-in functions
checkNotNull with accompanied exception message for easy debugging.
If you follow these 6 tips, you can remove all
!! from your Kotlin code. Your code will be safer, more debuggable and cleaner. Let me know in the comments if you know about more ways how to deal with null safety.