🐦 Kotlin Beginner

What does the apply scope function do in Kotlin?

Answer

The apply scope function executes a block where this refers to the object, and then returns the object itself (not the result of the block). This makes it ideal for object initialization and configuration — you can set multiple properties without repeating the variable name: val button = Button().apply { text = "OK"; isEnabled = true; setOnClickListener { ... } }. It returns the configured object, making it chainable. The apply block can access all members of the object directly without the it. prefix.