The Five Scope Functions

The Five Scope Functions in Kotlin: --- A watch repairer's bench is a place of deliberate focus.


The Analogy: The Watchmaker's Bench and the Job Card

A watch repairer's bench is a place of deliberate focus. When a customer's watch comes in, the repairer clamps its movement into the holder at the centre of the bench, under the lamp and the loupe. For as long as it sits in that holder it is the movement -- the one thing being worked on -- and everything the repairer does is understood to apply to it. Clamping a movement into the holder is what a scope function does: it takes one object and gives you a small, bounded stretch of work in which that object is the subject, then releases it when the work is done.

While the movement is clamped there are two ways to speak of it. The repairer can simply say "wind this, oil this, regulate this," never naming the watch because it is obviously the thing in the holder -- that is referring to the object as this, the implicit subject of every instruction. Or the repairer can write the watch's ticket number on the job card and refer to it by that number -- "number 47 needs a new mainspring" -- which is referring to the object as it, a name you can use and even rename. Both point at the same clamped movement; they differ only in whether the object is the unspoken subject or a named reference.

When the work is finished there are two different things the repairer might hand back across the counter. Sometimes the customer wants the watch itself returned -- cleaned, oiled, adjusted, the very same movement that came in. Sometimes the customer wants not the watch but a written verdict about it: an estimate, a yes-or-no on whether it can be saved, the number of jewels counted. These are the two possible results of a bounded piece of bench work: the object itself, handed back, or a fresh result computed from it. The five scope functions are simply the useful combinations of those two choices -- how you name the object, and what you get back.

The failure mode is a mismatch at the counter. A customer who expected the repaired watch back but receives only a slip of paper with an estimate has been given a result where they wanted the object; a customer who wanted a quick verdict but has the whole watch pressed back into their hands got the object where they wanted a result. Choosing the wrong scope function is exactly this: reaching for the one that hands back the object when you needed the computed value, or the reverse. And clamping two movements into the holder at once -- nesting one bench job inside another -- makes "this" hopelessly ambiguous, which is why a careful repairer works on one watch at a time.


Syntax or Core Structure

class Kettle {
    var litres: Int = 1
    var celsius: Int = 20
}

fun main() {
    val k = Kettle().apply {
        litres = 2
        celsius = 100
    }
    val checked = k.also { println("checked " + it.litres + "L") }
    val summary = with(k) { litres.toString() + "L at " + celsius + "C" }
    val boiling = k.let { it.celsius >= 100 }
    val doubled = run { k.litres * 2 }

    println(summary)
    println("boiling: " + boiling)
    println("doubled litres: " + doubled)
    println("checked is same: " + (checked === k))
}

All five appear here. apply configures the Kettle using this and returns the object, so k is the configured kettle. also runs a side effect using it and returns the object, so checked is that same kettle. with and let and run each return the result of their block: with groups member calls under this, let exposes the object as it, and the non-extension run just evaluates a block. Note the output order: the also prints where checked is assigned, before any of the four explicit println calls.

Output:

checked 2L
2L at 100C
boiling: true
doubled litres: 4
checked is same: true

Technical Depth: Two Axes, and the Return-Value Trap

The whole family reduces to two questions

Every one of the five is fixed by two decisions: how the object is referred to inside the block, and what the block hands back. The table below is the entire map. Read the middle column as how you name the object and the right column as what you receive.

FunctionRefers to the object asHands back
letitthe block's result
runthisthe block's result
withthisthe block's result
applythisthe object itself
alsoitthe object itself

with is the odd one syntactically -- it is not an extension, so you write with(obj) { ... } rather than obj.with { ... } -- but it belongs with run in behaviour. The single most common bug is choosing across the bottom split by accident: expecting apply or also to give you a computed value, or expecting let, run or with to give you the object back.

fun main() {
    val sb = StringBuilder("go")
    val configured = sb.apply { append("!") }
    val length = sb.let { it.length }
    println("apply returns builder: " + configured)
    println("let returns length: " + length)
    println("same object: " + (configured === sb))
}

Output:

apply returns builder: go!
let returns length: 3
same object: true

apply appends and returns the very same StringBuilder, so configured === sb is true and printing it shows go!. let returns whatever its block evaluates to -- here it.length, an Int -- so length is 3, the length of go! after the append. Same object went in; one call handed back the object, the other handed back a number.

let for null-safety, this as an implicit receiver

The pairing of ?. with let is the idiomatic "do this only when non-null." And a this-receiver function lets you drop the receiver entirely, calling members as bare names.

fun describe(name: String?): String =
    name?.let { "name has " + it.length + " chars" } ?: "no name"

fun main() {
    println(describe("York"))
    println(describe(null))

    val label = buildString {
        this.append("[")
        append("core")
        append("]")
    }
    println(label)
}

Output:

name has 4 chars
no name
[core]

For "York" the ?.let runs and computes the string; for null the whole ?.let is skipped and the elvis operator supplies "no name". Inside buildString, the receiver is a StringBuilder referred to as this, so this.append("[") and the bare append("core") are the same call written two ways.

also returns the object, so it chains

Because also hands back the object, it slots into the middle of a call chain to perform a side effect -- logging, validating, recording -- without interrupting the flow of values.

fun main() {
    val log = ArrayList<String>()
    val nums = listOf(3, 1, 2)
        .also { log.add("input size " + it.size) }
        .sorted()
        .also { log.add("sorted to " + it) }
    println("result: " + nums)
    println("log: " + log)
}

Output:

result: [1, 2, 3]
log: [input size 3, sorted to [1, 2, 3]]

Each also records a line and returns its receiver unchanged, so the chain continues: the first logs the input size and passes the list to sorted, the second logs the sorted list and passes it on to nums. The values flow through untouched while the side effects accumulate in log.


Real World Example: A Sensor Report Built with Scope Functions

The program reads Celsius sensor values, converts each to Fahrenheit, classifies it, and prints a board -- structuring the work with all five scope functions. apply configures each Reading, also records it in a status tally, run assembles the summary string, let transforms a nullable maximum, and with groups two calls on the entry list.

const val HOT = 200
const val COLD = 32
const val READINGS = "boiler:100,yard:15,cold:-40,oven:200,store:25"
const val W_NAME = 8
const val W_C = 6
const val W_F = 6
const val W_STATUS = 8

class Reading {
    var name: String = ""
    var celsius: Int = 0
    var fahrenheit: Int = 0
    var status: String = ""
}

fun classify(f: Int): String = when {
    f >= HOT -> "HOT"
    f <= COLD -> "COLD"
    else -> "WARM"
}

fun row(name: String, c: String, f: String, status: String): String =
    name.padStart(W_NAME) + c.padStart(W_C) + f.padStart(W_F) + status.padStart(W_STATUS)

fun main() {
    val entries = READINGS.split(",").map { it.split(":") }
    val ruleWidth = W_NAME + W_C + W_F + W_STATUS
    println(row("NAME", "C", "F", "STATUS"))
    println("-".repeat(ruleWidth))

    val order = listOf("HOT", "WARM", "COLD")
    val tally = IntArray(order.size)
    var sumF = 0
    for (e in entries) {
        val r = Reading().apply {
            name = e[0]
            celsius = e[1].toInt()
            fahrenheit = celsius * 9 / 5 + 32
            status = classify(fahrenheit)
        }
        sumF += r.fahrenheit
        r.also { tally[order.indexOf(it.status)] += 1 }
        println(row(r.name, r.celsius.toString(), r.fahrenheit.toString(), r.status))
    }
    println("-".repeat(ruleWidth))

    val summary = run {
        val parts = ArrayList<String>()
        for (i in order.indices) parts.add(order[i] + "=" + tally[i])
        parts.joinToString(" ")
    }
    println("status: " + summary)
    println("readings: " + entries.size + "  sumF: " + sumF)

    val hottest = entries.map { it[1].toInt() }.maxOrNull()?.let { it * 9 / 5 + 32 }
    println("hottest C to F: " + hottest)
    with(entries) {
        println("first " + first()[0] + " last " + last()[0])
    }

    val stale = Reading().apply {
        name = "probe"; celsius = 25; fahrenheit = celsius * 9 / 5 + 32; status = classify(fahrenheit)
    }
    stale.celsius = 100
    println("stale probe: C now " + stale.celsius + " but F still " + stale.fahrenheit +
        " status " + stale.status)
}

Output:

    NAME     C     F  STATUS
----------------------------
  boiler   100   212     HOT
    yard    15    59    WARM
    cold   -40   -40    COLD
    oven   200   392     HOT
   store    25    77    WARM
----------------------------
status: HOT=2 WARM=2 COLD=1
readings: 5  sumF: 700
hottest C to F: 392
first boiler last store
stale probe: C now 100 but F still 77 status WARM

Trace the cold row. Its Celsius is -40, and -40 * 9 / 5 + 32 is -360 / 5 + 32, that is -72 + 32, which is -40 -- the one temperature where the two scales meet. Its Fahrenheit is at or below COLD, so classify returns COLD. The Fahrenheit column sums to 700, and the tally counts two HOT readings (boiler and oven), two WARM (yard and store) and one COLD.

Each scope function does a distinct job. apply fills the four fields of a fresh Reading with this as the implicit subject and hands back the configured object. also takes that object as it, bumps the right slot of the tally, and returns it unchanged. run evaluates a block that builds the summary string and hands the string back. let runs only because maxOrNull returned a non-null maximum, converting the hottest Celsius of 200 to 392. with(entries) groups the first and last calls under one receiver.

The last line exposes the genuine design flaw. Reading is a bag of independent vars, and apply computes fahrenheit and status exactly once, at configuration time. Those derived fields are snapshots, not live values. The stale probe is built at 25 Celsius, so its Fahrenheit is 77 and its status WARM; then its celsius is set to 100, and nothing recomputes the rest, so it reports a contradiction -- 100 Celsius sitting beside a Fahrenheit of 77 and a status of WARM. apply gives the reassuring appearance of a properly configured object while establishing no invariant that keeps the fields consistent; the fix is to make fahrenheit and status computed properties on Reading rather than stored fields set once. Two narrower limits: the Celsius-to-Fahrenheit conversion uses integer division and truncates for any Celsius not divisible by 5, invisible here because every sample is; and padStart never truncates, so the first sensor name longer than eight characters would misalign the board.


Common Mistakes

  1. Using the result of apply or also as though it were the block's value. Both hand back the object, not what the block computed. Writing val n = list.also { it.size } binds n to the list, never to its size; the it.size result is discarded.
  1. Using let, run or with when you wanted the object back. These three return the block's result. If the block's last expression is an Int or a Boolean, that is what you get -- not the receiver -- so a configuration written in let throws the configured object away.
  1. Mixing up this and it between the two groups. In apply, run and with the object is this and members are called bare; in let and also it is it. Writing it.append(...) inside an apply, or a bare length inside a let, does not compile.
  1. Nesting scope functions until this and it are ambiguous. An apply inside another apply gives two this receivers, and the inner one shadows the outer. Deeply nested scope functions are a classic source of "which object is this?" confusion; flatten them or name the parameters.
  1. Expecting with to be null-safe. with takes its argument directly and does no null check. For a nullable receiver use ?.let or ?.run, which run the block only when the value is present.
  1. Reaching for apply or also to transform to a new type. Neither can change what is returned -- it is always the receiver. When you need to map the object to a different value or type, use let or run.
  1. Letting the elvis fallback fire when the let block itself returns null. In x?.let { compute() } ?: default, the default is used both when x is null and when compute() returns null. If the block can legitimately produce null, the fallback triggers in a case you did not intend.
  1. Configuring derived fields in apply and expecting them to stay current. An apply block runs once. If it computes a field from another mutable field, later changes to the source leave the derived field stale, because nothing recomputes it. Derived values belong in computed properties, not one-shot configuration.
  1. Reaching for a scope function where a plain local would read better. Not every object needs a bench. A named val and a couple of ordinary statements are often clearer than a chain of let, run and also, especially for a reader who then has to track what this and it mean at each step.

Best Practices

  • Choose by the two axes: if you need the object back, use apply or also; if you need a computed result, use let, run or with; use this when you make many member calls and it for a named single use.
  • Use apply for object configuration, where a freshly built object has several properties set before it is handed on.
  • Use also for side effects inside a chain -- logging, validation, recording -- so the values keep flowing while the effect happens on the side.
  • Use ?.let for "run this only when non-null" transforms, keeping the null handling and the transformation in one readable expression.
  • Use with to group several calls on a single non-null object you already hold, and run when you also want the block to produce a result.
  • Avoid nesting scope functions; when a block grows or needs a second object, extract a named function or bind explicit parameter names so no reader has to guess the receiver.
  • Prefer a plain named variable over a scope function whenever it reads more clearly, and reserve the scope functions for the cases where they genuinely tighten the code.
  • Establish invariants with computed properties or an init block on the type itself, not with an apply that runs once and leaves derived fields to drift out of date.

Practice Exercises

  1. Configure a mutable object with apply and, separately, compute a derived number from it with let. Bind each to a variable, then confirm with === and by printing the types that apply returned the object while let returned the number.
  1. Write firstLen(s: String?): Int that returns the string's length via ?.let or 0 via elvis. Test it on a non-null string and on null. Then change the let block so it can itself return null and describe exactly when the elvis fallback now fires.
  1. Build a list-processing chain that uses also twice to record two intermediate steps into a log list without breaking the chain of values. Print the final result and the log, and confirm the values were unaffected by the logging.
  1. Define a mutable class with a field configured in an apply block from another field, mutate the source field afterward, and show the derived field is now stale. Then refactor the derived field into a computed property and show the staleness is gone.