August 2017
Intermediate to advanced
440 pages
10h
English
Sometimes we need to create and initialize an object by calling some methods or modifying some properties, such as when we are creating a Button:
val button = Button(context)
button.text = "Click me"
button.isVisible = true
button.setOnClickListener { /* ... */ }
this.button = button
We can reduce code verbosity by using the apply extension function. We can call all these methods from the context where button is the receiver object:
button = Button(context).apply {
text = "Click me"
isVisible = true
setOnClickListener { /* ... */ }
}
Read now
Unlock full access