Kotlin allows us to perform null-safe method calls on variables that may, or may not, be null. One example of how this can reduce boilerplate in our code is in the handling of savedInstanceState.
A common pattern is to check whether savedInstanceState is non-null within onCreate(), and if it is, handle the restoration of that state. We can see an example of this in the following code snippet:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
savedInstanceState?.let { it }
}
fun restoreSavedState(savedInstanceState: Bundle) {
// restore state
}
Using a null-safe call to the let() function, we can safely restore our state only if savedInstanceState is non-null. And because of smart casting in Kotlin, we can define the restoreSavedState() function to only accept a non-null Bundle and then rely on the compiler to smart cast savedInstanceState for us. This helps us to enforce type safety and reduce NullPointerExceptions.
These have been just a couple of examples of how Kotlin can quickly make writing Android code safer and more concise. In the next section, we'll see how Kotlin can be applied to the build configuration of our project.