apply and with: Configure and Return
Use apply and with to configure objects and understand their return values.
Scope Function Recap
Kotlin's scope functions (apply, also, let, run, with) let you execute a block in the context of an object. Each differs by receiver (this vs it) and return value.
apply Basics
apply { ... } runs the block with this bound to the receiver and returns the receiver itself. Perfect for object configuration.
class Person {
var name: String = ""
var age: Int = 0
}
fun main() {
val p = Person().apply {
name = "Ada"
age = 35
}
println("${p.name}, ${p.age}")
}All lessons in this course
- apply and with: Configure and Return
- let and run: Transform and Scope
- also: Side Effects Without Changing the Receiver
- Choosing the Right Scope Function: Decision Guide