typestar

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

  1. apply runs a block on the receiver and returns the receiver — setup in place.
  2. let maps a value through a block and returns the block's result.
  3. also peeks at a value for a side effect and passes it through.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Idioms, step 19 of 27 in Language basics.

← Previous Next →