August 2017
Intermediate to advanced
440 pages
10h
English
Sometimes, we know that a property won't be null, but it won't be initialized with the value at declaration time. Let's look at a common Android example--retrieving a reference to a layout element:
class MainActivity : AppCompatActivity() {
private var button: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
button = findViewById(R.id.button) as Button
}
}
The button variable can't be initialized at declaration time because the MainActivity layout is not yet initialized. We can retrieve the reference to the button defined in the layout inside the onCreate method, but to do this we need to declare a variable as nullable (Button?).
Such an approach seems quite ...
Read now
Unlock full access