Carl Rice

View Original

Kotlin Bricks: Avoid lots of safe dereference using apply

Coming from a Java background its very common to null check quite a bit to avoid the billon dollar mistake. Kotlin solves this by introducing a null variant to every type so when you get the dreaded NullPointerException its probably a serious issue you should deal with. When starting out with Kotlin your instinct says drop ? everywhere, you know, just to be safe.

Consider this example where we did a good job to guard against a crash should onNetworkSuccess return after our UI has been destroyed. While simple, there are still three textView? and you could imagine it growing pretty quickly as you make a more complex UI.

See this content in the original post

As an alternative we can use the apply function to not only use the safe operator once but also avoid any unnecessary work if the view ends up being null. I think the code also read better this way.

See this content in the original post