The Analogy: Player-Piano Rolls and the Bench Tally Counter
In the corner of an old music hall stands a pianola -- a player piano that performs whatever perforated paper roll you feed into it. The piano itself knows nothing of any particular tune. Hand it a roll and it plays the roll; swap in another and it plays that instead. The roll is the interesting thing: a portable, storable, hand-around encoding of what to do, entirely separate from the machine that does it. A shelf behind the piano holds a rack of dozens of rolls, and the operator can pick one out, pass it along, or keep a stack ready. In exactly this way a lambda is behaviour turned into a value -- a block of actions you can store in a variable, keep in a list, and hand to a function. The pianola is the higher-order function: a machine defined by the fact that it accepts a roll and performs it.
Some rolls carry a margin note instead of punching every detail into the paper. A note might read "transpose everything up by the number chalked on the bench tally counter." When the pianola reaches that roll, it glances at the bench counter and shifts the tune accordingly. The roll has captured its surroundings: it does not hold the transposition itself, it holds a reference to the counter and reads it at the moment of performance. This is a closure -- a lambda that reaches out and grabs a variable from the scope where it was written, and consults that variable when it finally runs, not when it was cut.
The distinction that trips up every apprentice is which surroundings a roll captures. Suppose the operator cuts a fresh roll for each of three songs, and for each song chalks the transposition onto that song's own little slate, one slate per roll. Every roll reads its own slate and plays its own number -- one, then two, then three. But suppose instead every roll carries the note "read the one bench tally counter," and the operator bumps that single counter between cuts. Now all three rolls reference the same counter, and when they are finally performed the counter reads three, so every roll transposes by three. One roll per private slate remembers its own value; many rolls sharing one counter all see the final value.
The failure mode is the roll filed away and performed months later. A roll that punched its transposition directly into the paper plays the same tune forever. But a roll whose margin note says "read the bench counter" reads whatever the counter happens to say on the day it is finally performed -- and if the bench was cleared, the counter reset, or someone bumped it in the meantime, the roll plays a tune its cutter never intended. Behaviour that captures a living, changing variable is not a photograph of that variable; it is a standing instruction to go and look, and what it finds depends entirely on when it looks.
Syntax or Core Structure
fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))
fun combine(a: Int, b: Int, op: (Int, Int) -> Int): Int = op(a, b)
fun main() {
println(applyTwice(3) { it + 1 })
println(combine(6, 4) { x, y -> x * y })
val add: (Int, Int) -> Int = { a, b -> a + b }
println(combine(6, 4, add))
val nums = listOf(5, 2, 8, 1)
println("evens: " + nums.filter { it % 2 == 0 })
println("sorted: " + nums.sortedBy { it })
}
A lambda is written in braces: parameters before the ->, body after, and the last expression is its result. applyTwice and combine are higher-order functions -- their types (Int) -> Int and (Int, Int) -> Int name a function as a parameter. When the lambda is the last argument, it moves outside the parentheses (the trailing-lambda form), and a single parameter can be referred to as it instead of being named. A lambda can also be stored in a variable, as add shows, and passed by name. The final two lines feed lambdas to the standard-library functions filter and sortedBy.
Output:
5
24
10
evens: [2, 8]
sorted: [1, 2, 5, 8]
applyTwice(3) { it + 1 } computes f(f(3)), that is f(4), which is 5. combine(6, 4) { x, y -> x * y } multiplies to 24, while the stored add sums to 10.
Technical Depth: Closures, Capture and the Two Kinds of Return
A closure captures the variable, not its value at the time
Unlike Java, where a captured local must be effectively final, a Kotlin lambda can capture a mutable var and both read and write it. The lambda holds a reference to the variable itself, so it sees every later change, and its own writes are visible outside.
fun main() {
var tally = 0
val bump = { tally += 10 }
bump()
bump()
println("after two bumps: " + tally)
val readers = ArrayList<() -> Int>()
for (i in 1..3) {
readers.add { i }
}
println("per-iteration: " + readers.map { it() })
var shared = 0
val sharers = ArrayList<() -> Int>()
for (j in 1..3) {
shared = j
sharers.add { shared }
}
println("one shared var: " + sharers.map { it() })
}
Output:
after two bumps: 20
per-iteration: [1, 2, 3]
one shared var: [3, 3, 3]
The bump closure writes to tally, and after two calls the variable read outside is 20. The two loops show the capture distinction the analogy warned about. The loop variable i is a fresh binding on each iteration, so each stored lambda captures its own i and the list reads back [1, 2, 3]. But shared is one variable declared outside the loop; all three lambdas capture that same variable, and by the time they run it holds its final value 3, so they all read 3.
Non-local return, and how anonymous functions differ
A lambda passed to an inline function -- which includes forEach and most standard-library higher-order functions -- may contain a bare return that returns from the enclosing named function, not just the lambda. This is a non-local return. To return only from the lambda, use a labelled return@forEach. An anonymous function behaves differently: a return inside it returns from the anonymous function itself.
fun firstEven(xs: List<Int>): Int {
xs.forEach { if (it % 2 == 0) return it }
return -1
}
fun countPositives(xs: List<Int>): Int {
var count = 0
xs.forEach {
if (it < 0) return@forEach
count += 1
}
return count
}
fun main() {
println("first even: " + firstEven(listOf(1, 3, 6, 8)))
println("positives: " + countPositives(listOf(1, -2, 3, -4, 5)))
}
Output:
first even: 6
positives: 3
In firstEven, the bare return it exits the whole function the moment 6 is found, so the trailing return -1 is never reached. In countPositives, return@forEach skips only the current element -- it acts like continue -- and the negatives are passed over, leaving three positives counted.
The table fixes the four forms of function type and value you will meet. Read the middle column as what the syntax denotes and the right as the key behaviour.
| Form | What it denotes | Key behaviour |
|---|---|---|
| lambda in braces | an anonymous function value | last expression is the result |
| the name it | the sole parameter | only when there is exactly one |
| trailing lambda | last argument moved outside the call | reads as a built-in block |
| bare return in a lambda | return from the enclosing function | non-local, only in inline calls |
Real World Example: A Ledger Summarised by Higher-Order Functions
The program reads a day's ledger -- named amounts, positive for credits and negative for debits -- prints a running balance, and then summarises it entirely through higher-order functions. report is itself a higher-order function: it takes a predicate lambda and totals the amounts that satisfy it, so credits and debits are the same function called with different lambdas. fold computes the net, and maxByOrNull finds a headline figure.
const val LEDGER = "opening:1000,rent:-450,delivery:600,fuel:-280,market:880,repairs:-400"
const val W_NAME = 10
const val W_AMOUNT = 8
const val W_BAL = 9
fun report(entries: List<Pair<String, Int>>, keep: (Int) -> Boolean): Int =
entries.map { it.second }.filter(keep).sum()
fun row(name: String, amount: String, bal: String): String =
name.padStart(W_NAME) + amount.padStart(W_AMOUNT) + bal.padStart(W_BAL)
fun main() {
val entries = LEDGER.split(",").map {
val parts = it.split(":")
parts[0] to parts[1].toInt()
}
val ruleWidth = W_NAME + W_AMOUNT + W_BAL
println(row("NAME", "AMOUNT", "BALANCE"))
println("-".repeat(ruleWidth))
var balance = 0
for ((name, amount) in entries) {
balance += amount
println(row(name, amount.toString(), balance.toString()))
}
println("-".repeat(ruleWidth))
val credits = report(entries) { it > 0 }
val debits = report(entries) { it < 0 }
val net = entries.fold(0) { acc, e -> acc + e.second }
val largest = entries.maxByOrNull { it.second }!!
println("entries: " + entries.size)
println("credits " + credits + " debits " + debits + " net " + net)
println("net " + net + " = final balance " + balance + " agree: " + (net == balance))
println("largest by value: " + largest.first + " " + largest.second)
val demo = listOf(1, -5000, 2)
println("max of " + demo + " by value: " + demo.maxByOrNull { it }!!)
}
Output:
NAME AMOUNT BALANCE
---------------------------
opening 1000 1000
rent -450 550
delivery 600 1150
fuel -280 870
market 880 1750
repairs -400 1350
---------------------------
entries: 6
credits 2480 debits -1130 net 1350
net 1350 = final balance 1350 agree: true
largest by value: opening 1000
max of [1, -5000, 2] by value: 2
Trace the balance column. It starts at zero and adds each amount in turn: opening brings it to 1000, rent of -450 drops it to 550, delivery lifts it to 1150, fuel cuts it to 870, market raises it to 1750, and repairs leaves it at 1350. The credits are the three positive amounts summed to 2480, the debits are the three negatives summed to -1130, and their sum is the net of 1350.
Every summary line runs on a lambda. report(entries) { it > 0 } passes the predicate { it > 0 } into a function typed (Int) -> Boolean, and inside, map projects each pair to its amount, filter keeps the ones the predicate accepts, and sum adds them. The very same report with { it < 0 } produces the debits, which is the whole point of a higher-order function: the behaviour that varies is handed in as a value. fold(0) { acc, e -> acc + e.second } threads an accumulator through the list to compute the net, and maxByOrNull takes a selector lambda that picks which field to rank on.
Two lines below the board deserve suspicion. The net ... = final balance ... agree: true line is a tautology: the running balance adds every amount, and net folds every amount, so both are the same sum by construction and the line would print true however the amounts were chosen. The genuine design flaw is in largest. maxByOrNull { it.second } ranks by signed value, not by magnitude, so it reports the most positive entry and is blind to large losses. Here it returns opening 1000, which looks right only because the biggest credit also happens to be the biggest movement. The final line exposes the trap on purpose: in [1, -5000, 2] the genuinely largest movement is the loss of 5000, but maxByOrNull by value returns 2, because -5000 is the smallest number, not the largest. A report that wanted the biggest movement should have ranked on kotlin.math.abs(it.second). As ever, a narrower limit is that padStart never truncates, so the first ledger name longer than ten characters would misalign the board.
Common Mistakes
- Assuming a bare
returnin a lambda returns only from the lambda. In a lambda passed to an inline function, a barereturnreturns from the enclosing named function -- a non-local return. If you meant to leave only the lambda, you must write a labelledreturn@forEach(or the relevant label), or you will exit far more than you intended.
- Expecting a non-local return from a lambda passed to a non-inline function. The non-local
returnis only legal when the higher-order function isinline. Store a lambda in a variable or pass it to a non-inline function and a barereturnwill not compile, because the lambda outlives the caller's frame.
- Using
itwhen the lambda has more than one parameter.itnames the sole parameter and exists only for single-parameter lambdas. A two-parameter lambda must name both, as in{ a, b -> ... }; there is noitto reach the second argument.
- Believing a closure captures a snapshot of the variable's value. A closure captures the variable, not a copy of its current value. If the captured
varchanges after the lambda is created, the lambda sees the new value when it runs. Capturing a loop-scoped variable and a variable declared outside the loop give famously different results.
- Assuming every stored lambda is free. A lambda passed to an
inlinefunction is inlined with no object allocated, but a lambda stored in a variable, put in a list, or passed to a non-inline function becomes a real function object on the heap. In a hot path the difference between the two is measurable.
- Shadowing
itin nested lambdas. When oneit-lambda is nested inside another, the innerithides the outer one and there is no way to reach the outer parameter. Name the parameters explicitly whenever lambdas nest, or you will silently refer to the wrong value.
- Getting the lambda's arity wrong for the expected function type. A parameter typed
(Int) -> Intdemands a one-argument lambda; supplying{ a, b -> a + b }is a type error, and supplying{ 42 }where a parameter was expected quietly ignores the argument. Match the lambda's shape to the declared function type.
- Confusing an anonymous function's
returnwith a lambda's. Areturninside an anonymous functionfun(x: Int): Int { return x }returns from that anonymous function, never from the enclosing one. Reaching for an anonymous function precisely because you want a localreturnis the idiomatic fix when a lambda's non-local return is unwanted.
- Treating the last expression as ignored. A lambda's result is its last expression, with no
returnkeyword. Adding a stray trailing expression, or forgetting that the last line is the value, produces a lambda that returns something other than you expect -- particularly easy with a trailingprintln, whose result isUnit.
Best Practices
- Let the last expression be the lambda's result rather than reaching for
return, and reserve explicit returns for the non-local and anonymous-function cases where they are actually needed.
- Use
itonly for short single-parameter lambdas; name the parameter as soon as the lambda grows, nests, or takes more than one argument, so no reader has to guess whatitrefers to.
- Prefer the trailing-lambda form for the last argument, which lets calls like
filter { ... }read as built-in blocks rather than nested parentheses.
- Reach for the standard-library higher-order functions --
map,filter,fold,sumOf-- over hand-written loops when they express the intent more directly, since they are inline and allocate nothing.
- Keep lambdas short; when one grows past a few lines or gains a name worth having, promote it to a named function and pass a reference instead.
- Be deliberate about capturing mutable variables, and remember that a captured
varis read at call time; if you need the value at capture time, copy it into avalfirst.
- Use
_for a lambda parameter you do not use, so a reader sees at a glance which arguments the body actually consults.
- Choose an anonymous function over a lambda when you need an explicit return type or a local
return, and a lambda otherwise for its lighter syntax.
Practice Exercises
- Write a higher-order function
applyN(x: Int, n: Int, f: (Int) -> Int): Intthat appliesftoxexactlyntimes. Call it to triple a number twice and to increment a number five times, and verify each result against a hand trace.
- Reproduce the capture distinction: in one loop store lambdas that each capture the loop variable, and in another store lambdas that all capture a single
vardeclared outside the loop. Print what each list of lambdas returns and explain why one reads back[1, 2, 3]and the other reads back the same value three times.
- Compute the sum of the squares of the even numbers in a list two ways -- once with a chain of
filter,mapandsum, and once with an explicitforloop -- and confirm the two agree. State which higher-order function each loop step corresponds to.
- Write
firstMatch(xs: List<Int>, pred: (Int) -> Boolean): Intthat returns the first element satisfyingpredusingforEachwith a non-localreturn, and-1if none match. Then writecountMatchesthat usesreturn@forEachto skip non-matching elements, and explain why one uses a bare return and the other a labelled one.