Part 10 / Topic 4 of 8
Scope functions: let, run, with, apply, also
A scope function runs a block against a receiver and hands back either the block's result
or the receiver itself, under a temporary name (it or this). All five exist to avoid an
extra throwaway val when all you need is "do something with this value, briefly."
// let: block result, receiver as `it` -- the classic null-safe-chaining use.
val summary = found?.let { "${it.id} to ${it.city}" } ?: "not found"
// run: block result, receiver as `this` -- handy when the block touches several of the
// receiver's own members without an `it.` prefix each time.
val price = found?.run { weightKg * 0.35 }
// with: block result, receiver as `this`, but NOT an extension -- passed as a plain argument,
// for when you already have a non-null value and don't need the `?.` chain.
val line = with(StringBuilder()) { append("Route: "); append(found?.city); toString() }
// apply: returns the RECEIVER, as `this` -- configure an object, get the same object back.
val tags = mutableListOf<String>().apply { add("fragile"); add("priority"); sort() }
// also: returns the RECEIVER, as `it` -- a side effect (logging, printing) inserted into a
// chain without breaking it.
val delayedOnly = SHIPMENTS.filter { it.delayed }.also { println("found ${it.size}") }.map { it.id }
let: S-2004 to Chennai
run: ₹840.0
with: Route: Chennai (2400.0 kg)
apply: [fragile, priority]
also: found 2 delayed shipment(s)
Delayed ids: [S-2002, S-2004]
The decision rule:
| Function | Returns | Receiver as | Reach for it when... |
|---|---|---|---|
let |
block result | it |
transforming a nullable, or naming a long expression briefly |
run |
block result | this |
computing a result from several of the receiver's own members |
with |
block result | this |
you already have a non-null receiver, called as with(x) { ... } |
apply |
the receiver | this |
configuring/building an object, then using the same object |
also |
the receiver | it |
a side effect (log/print/assert) that shouldn't break a chain |
let/run/with return the block's result; apply/also return the receiver
unchanged. That single fact covers most "which one do I want here" decisions.
Full program: examples/04_scope_functions.kt.
Done here? The practice set for Part 10 — including the solutions — is on the part page.