Configuring a view reference

To get an immutable reference to a button, we could use something along the lines of the following code snippet:

val button = findViewById<Button>(R.id.button)

If we then wanted to configure multiple properties on that button, we could make use of the scoping function, apply:

val button = findViewById<Button>(R.id.button).apply {
text = "Hello Kotlin"
gravity = Gravity.START
setTextColor(resources.getColor(R.color.colorAccent))
}

The apply function provides us with a receiver, in this case, Button, which can then be referenced implicitly within the scope of the passed lambda. This can be a useful means of grouping related method calls or property updates.