apply and also
Configure and side-effect.
Configuring Objects
apply and also are scope functions that return the object itself rather than the lambda result. This makes them perfect for configuration and chaining.
The apply Function
apply runs a block with the object as this and returns the object. It is the classic tool for initializing an object after creation.
fun main() {
val builder = StringBuilder().apply {
append("Hello")
append(", ")
append("World")
}
println(builder.toString())
}All lessons in this course
- let and run
- apply and also
- with
- Choosing the Right One