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.

var textView: TextView? = null

override fun onCreate(si: Bundle?) {
    super.onCreate(si)
    textView = findViewById(R.id.tv) as TextView?
}

fun onNetworkSuccess(message: String) {
    if (message.isNotEmpty()) {
        textView?.text = message
        textView?.visibility = VISIBLE
    } else {
        textView?.visibility = GONE
    }
}

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.

fun onNetworkSuccess(message: String) {
    textView?.apply {
        if (message.isNotEmpty()) {
            text = message
            visibility = VISIBLE
        } else {
            visibility = GONE
        }       
    }
}