Scope functions in Kotlin
apply, let and also: tiny blocks that keep configuration close.
class PackList {
val items = mutableListOf<String>()
var owner = ""
}
fun main() {
// apply configures the receiver and hands it back.
val pack = PackList().apply {
owner = "Rae"
items += listOf("stove", "map", "rope")
}
// let works on a value; also peeks without breaking the chain.
val summary = pack.items.let { "${it.size} items for ${pack.owner}" }
println(summary)
pack.items.also { println("Last packed: ${it.last()}") }
}
How it works
applyruns a block on the receiver and returns the receiver — setup in place.letmaps a value through a block and returns the block's result.alsopeeks at a value for a side effect and passes it through.
Keywords and builtins used here
PackListStringclassfunitmainvalvar
The run, in numbers
- Lines
- 16
- Characters to type
- 431
- Tokens
- 105
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 97 seconds.
Step 1 of 3 in Idioms, step 19 of 27 in Language basics.