The Analogy: The Colliery Cage and the Bell Signals
A deep colliery shaft is not a lift with buttons. The cage hangs from a rope wound onto a drum in an engine house at the surface, and the man at the drum -- the winding engineman -- cannot see down the shaft at all. He works entirely from a code of bells. Along the shaft there are insets, small landings cut into the rock at each working level, and at every inset stands an onsetter with a bell pull. When the onsetter has loaded the cage he rings, the engineman reads the code, and the drum turns.
The code is short and every man underground knows it by heart. One bell means raise to the next inset up: the cage lifts and stops at the first landing it comes to. Three bells means raise to the surface and do not stop for anybody, no matter how many insets the cage passes on the way. Two bells means lower. A single tap means hold where you are, the loading is not finished. The number of bells is not a measure of urgency or distance -- it names a destination, and the difference between naming one and letting the machinery pick for you is the whole of this lesson.
Most of the time the default is what you want. An onsetter at the lowest level taps once between tubs and rings once when the cage is full; it rises one landing to the next man, who does the same, so work travels up the shaft one inset at a time and nobody needs the layout of the whole mine. But sometimes the default is exactly wrong: a fireman who has found gas at the deepest level does not want the cage stopping at four landings with a hundred men waiting to load it. He rings three, the destination is named, and every inset between is passed.
The failure mode is the onsetter who means the surface and rings one bell. The cage rises one landing and stops. The deputy at that landing sees a cage arrive, assumes it has come for him, and starts loading tubs into it -- on top of a fireman who is trying to get out. Nothing has broken, no rule has been violated, and the engine house has no way to know: the signal was valid, it simply named the wrong destination. That is precisely what an unlabelled break does inside a nested loop. It leaves the inner loop, the outer loop carries calmly on to its next pass, and the answer you get back is plausible, arrives late, and is wrong.
Syntax or Core Structure
A label is a name, an @, and a loop: search@ for (...). Once a loop has a name, break@search and continue@search can address it from any depth inside. Without a name, break and continue always mean the nearest enclosing loop and nothing else.
fun main() {
val levels = listOf(
listOf(40, 55, 0, 70),
listOf(60, 0, 45),
listOf(80, 90, 65)
)
var scanned = 0
var found = "none"
search@ for (i in levels.indices) {
for (j in levels[i].indices) {
scanned++
if (levels[i][j] == 0) {
found = "level " + i + " tub " + j
break@search
}
}
}
println("labelled break found " + found + " in " + scanned + " checks")
var again = 0
var plausible = "none"
for (i in levels.indices) {
for (j in levels[i].indices) {
again++
if (levels[i][j] == 0) {
plausible = "level " + i + " tub " + j
break
}
}
}
println("bare break ended at " + plausible + " in " + again + " checks")
var loaded = 0
tubs@ for (i in levels.indices) {
for (weight in levels[i]) {
if (weight == 0) continue@tubs
loaded += weight
}
}
var allTubs = 0
var allWeight = 0
for (level in levels) {
for (weight in level) {
allTubs++
allWeight += weight
}
}
println("loaded " + loaded + " cwt of " + allWeight + " cwt over " + allTubs + " tubs")
println("abandoned by continue@tubs: " + (allWeight - loaded) + " cwt")
}
Output:
labelled break found level 0 tub 2 in 3 checks
bare break ended at level 1 tub 1 in 8 checks
loaded 390 cwt of 505 cwt over 10 tubs
abandoned by continue@tubs: 115 cwt
Read the first two lines together: they are the same search written twice and they do not agree. The labelled version stops the instant it finds an empty tub -- three checks, level 0 tub 2. The bare break finds that same tub, leaves the inner loop, and then the outer loop does what outer loops do: it starts level 1, finds the empty tub there too, overwrites the answer, and walks level 2 for good measure. Eight checks, and the reported answer is the last empty tub rather than the first. Neither run crashed and both printed a real location, which is what makes this bug expensive.
The third loop shows continue@tubs doing the opposite job -- not leaving the outer loop but starting its next pass early. The moment an empty tub turns up the rest of that level is abandoned, so level 0 contributes 40 and 55 but not the 70 behind the gap, and level 1 contributes 60 but not 45. Level 2 has no gap, so all of it counts: 390 cwt taken out of 505 cwt present, the missing 115 being that 70 and that 45.
Technical Depth: What a Label Can and Cannot Name
Kotlin has exactly three jump expressions -- break, continue and return -- and a label is a way of qualifying which construct a jump is talking about. A label is written name@ immediately before a loop or a lambda, and it is referenced with @name glued to the jump.
| Written | Where control lands | Label required |
|---|---|---|
break | just after the innermost enclosing loop | no |
break@outer | just after the loop labelled outer | yes |
continue | the next pass of the innermost enclosing loop | no |
continue@outer | the next pass of the loop labelled outer | yes |
return inside an inlined lambda | out of the enclosing named function | no |
return@forEach | out of that one call of the lambda only | the implicit function-name label |
return@mine | out of the lambda written with the label mine | yes |
The last three rows are where the confusion lives, because a lambda is not a loop and yet it usually sits where a loop body would. break and continue are simply not available inside a lambda: there is no loop to leave, only a function call to come back from. What a lambda gets instead is return, and inside a lambda passed to an inline function -- forEach, map, let, run, repeat and most of the standard library -- a bare return means something surprisingly strong. Pass that same lambda to a non-inline function, or to a parameter marked noinline or crossinline, and the bare form stops compiling outright.
Non-local return, and the label that only skips
A bare return inside a lambda that was passed to an inline function returns from the enclosing named function, not from the lambda. This is called a non-local return, and it is only possible because the compiler copies the lambda body into the caller, so the return compiles down to a genuine return instruction in the caller's own frame. If you want to leave only the lambda -- the equivalent of continue -- you must say so with a label, and the label you get for free is the name of the function the lambda was passed to.
fun firstEmptyTub(levels: List<List<Int>>): String {
levels.forEachIndexed { i, level ->
level.forEachIndexed { j, weight ->
if (weight == 0) return "level " + i + " tub " + j
}
}
return "none"
}
fun countEmptyTubs(levels: List<List<Int>>): Int {
var seen = 0
levels.forEach { level ->
level.forEach { weight ->
if (weight != 0) return@forEach
seen++
}
}
return seen
}
fun main() {
val levels = listOf(
listOf(40, 55, 0, 70),
listOf(60, 0, 45),
listOf(80, 90, 65)
)
println("first empty: " + firstEmptyTub(levels))
println("empty count: " + countEmptyTubs(levels))
println("nothing empty: " + firstEmptyTub(listOf(listOf(10, 20), listOf(30))))
var laps = 0
val partial = run tally@ {
var t = 0
for (n in listOf(1, 2, 3, 4)) {
laps++
if (n == 3) return@tally t
t += n
}
t
}
println("labelled run gave " + partial + " after " + laps + " laps")
}
Output:
first empty: level 0 tub 2
empty count: 2
nothing empty: none
labelled run gave 3 after 3 laps
firstEmptyTub is two nested forEachIndexed calls with no loop anywhere, and yet the return in the middle of the inner lambda walks straight out of both lambdas and out of firstEmptyTub itself, carrying a value. That is the labelled-break behaviour of the first example, obtained for free. countEmptyTubs wants the other thing -- skip this weight, keep counting -- so writing return there would abandon the whole count and hand back whatever had been accumulated. It writes return@forEach instead, which lands after the current lambda call and lets forEach proceed. The two spellings differ by eight characters and by an entire order of control flow.
The free label is not the only one available. run tally@ { ... } names the lambda itself, and return@tally t hands t back as the value of the whole run expression, so partial is 3: the loop added 1 and 2, met 3 on its third lap, and left. laps reading 3 rather than 4 is the check that the jump really happened instead of the loop merely running out.
Real World Example: A Winding Engine's Shift Log
A colliery clerk has the day's winding log: shifts, each a sequence of cage runs, each run a set of tub weights. An empty tub is noted and ignored. A run over the cage's safe load is refused and the next run tried -- a continue that must reach past the tub loop. A shift past its daily quota is closed where it stands. And a negative weight means the weighbridge has failed, which stops the shaft: a break that must reach past two loops.
const val SHIFTS =
"A:120+180/0+140/200;B:150+160/280/120;C:90+110/0/80+20/300/220/130;D:200/250/-5+260/150;E:100/200"
const val SAFE = 300
const val QUOTA = 700
val STATUSES = listOf("FULL", "CLOSED", "FAULT")
const val W_SHIFT = 7
const val W_RUNS = 6
const val W_TAKEN = 7
const val W_REFUSED = 9
const val W_LEFT = 6
const val W_LOADED = 8
const val W_STATUS = 9
fun row(shift: String, runs: String, taken: String, refused: String,
left: String, loaded: String, status: String): String =
shift.padStart(W_SHIFT) + runs.padStart(W_RUNS) + taken.padStart(W_TAKEN) +
refused.padStart(W_REFUSED) + left.padStart(W_LEFT) +
loaded.padStart(W_LOADED) + status.padStart(W_STATUS)
fun main() {
val width = W_SHIFT + W_RUNS + W_TAKEN + W_REFUSED + W_LEFT + W_LOADED + W_STATUS
val records = SHIFTS.split(";")
val tally = IntArray(STATUSES.size)
val names = mutableListOf<String>()
val loads = mutableListOf<Int>()
var tRuns = 0
var tTaken = 0
var tRefused = 0
var tLeft = 0
var tLoaded = 0
var tEmpty = 0
var reached = 0
var stoppedAfter = "none"
println(row("SHIFT", "RUNS", "TAKEN", "REFUSED", "LEFT", "LOADED", "STATUS"))
println("-".repeat(width))
shifts@ for (record in records) {
val head = record.split(":")
val name = head[0]
val runs = head[1].split("/")
var taken = 0
var refused = 0
var loaded = 0
var status = "FULL"
reached++
perRun@ for (r in runs.indices) {
val tubs = runs[r].split("+").map { it.toInt() }
var runTotal = 0
for (t in tubs.indices) {
val w = tubs[t]
if (w == 0) {
tEmpty++
continue
}
if (w < 0) {
println("scale fault: shift " + name + " run " + r +
" tub " + t + " read " + w + " cwt")
println(row(name, runs.size.toString(), taken.toString(),
refused.toString(), (runs.size - taken - refused).toString(),
loaded.toString(), "FAULT"))
stoppedAfter = name
break@shifts
}
runTotal += w
if (runTotal > SAFE) {
refused++
continue@perRun
}
}
taken++
loaded += runTotal
if (loaded > QUOTA) {
status = "CLOSED"
break@perRun
}
}
tally[STATUSES.indexOf(status)]++
names.add(name)
loads.add(loaded)
tRuns += runs.size
tTaken += taken
tRefused += refused
tLeft += runs.size - taken - refused
tLoaded += loaded
println(row(name, runs.size.toString(), taken.toString(), refused.toString(),
(runs.size - taken - refused).toString(), loaded.toString(), status))
}
println("-".repeat(width))
var tallied = 0
for (v in tally) tallied += v
println(row("TOTALS", tRuns.toString(), tTaken.toString(), tRefused.toString(),
tLeft.toString(), tLoaded.toString(), tallied.toString() + " SHIFTS"))
println("status: " + STATUSES.mapIndexed { i, s -> s + "=" + tally[i] }.joinToString(" "))
println("runs " + tRuns + " = taken " + tTaken + " + refused " + tRefused +
" + left " + tLeft + " agree: " + (tTaken + tRefused + tLeft == tRuns))
println("loaded " + tLoaded + " cwt empty tubs " + tEmpty +
" safe " + SAFE + " per run quota " + QUOTA + " per shift")
var sum = 0
for (v in loads) sum += v
println("per shift: " + names.indices.joinToString(" ") { names[it] + "=" + loads[it] } +
" sum " + sum + " agree: " + (sum == tLoaded))
println("shifts offered " + records.size + " reached " + reached +
" stopped after " + stoppedAfter)
}
Output:
SHIFT RUNS TAKEN REFUSED LEFT LOADED STATUS
----------------------------------------------------
A 3 3 0 0 640 FULL
B 3 2 1 0 400 FULL
C 6 5 0 1 820 CLOSED
scale fault: shift D run 2 tub 0 read -5 cwt
D 4 2 0 2 450 FAULT
----------------------------------------------------
TOTALS 12 10 1 1 1860 3 SHIFTS
status: FULL=2 CLOSED=1 FAULT=0
runs 12 = taken 10 + refused 1 + left 1 agree: true
loaded 1860 cwt empty tubs 2 safe 300 per run quota 700 per shift
per shift: A=640 B=400 C=820 sum 1860 agree: true
shifts offered 5 reached 4 stopped after D
Follow the shifts down the board. Shift A offers three runs and all three are taken: 300 cwt, then 140 cwt from a run whose first tub was empty, then 200 cwt, totalling 640 and leaving the quota untouched. Shift B's first run is 150 plus 160, which crosses the 300 cwt safe load on the second tub, so continue@perRun throws the whole run away -- B's LOADED of 400 is 280 plus 120 and holds no trace of the 310 that was weighed and rejected. Shift C runs on until its fifth run pushes the day's total to 820, past the 700 quota, and break@perRun closes it with one run still in the book: the 1 in its LEFT column. Shift D weighs a tub at -5 cwt, which is not a light tub but a broken weighbridge, and break@shifts stops the shaft -- E appears nowhere, because E was never reached.
Two of those three jumps are issued from inside the tub loop, and neither of them is talking about the tub loop -- which is the whole reason the labels are there. On the refusal, a bare continue would advance to the next tub of the run being refused, so the run would keep accumulating, refused could be incremented several times over, and the bottom of the run loop would then take and load the very run that had just been rejected. On the scale fault, a bare break would leave the tub loop, drop into taken++, credit the shift with the abandoned run, and then move on to run 3 and to shift E on a weighbridge already known to be lying. The third jump, the quota break, sits directly in the run loop where a plain break would behave identically; it is written break@perRun only so that all three exits from this nest name their destination out loud, in the same spirit as an onsetter who rings the code for the level he is actually standing at.
The audit lines are the arithmetic that makes the board trustworthy. runs 12 = taken 10 + refused 1 + left 1 says every run offered was accounted for exactly once, in one of three ways. The per shift line re-adds the loaded column from a separate list built as the loop went, so a total that drifted from its parts would show up here. empty tubs 2 matches the two zero weights in the log. And shifts offered 5 reached 4 stopped after D is the only line that records the shaft stop, worth printing because the board gives no hint that a fifth shift ever existed.
Now the limits, and the first one is serious. Compare the TOTALS row with the rows above it: four shifts are printed and the status cell says 3 SHIFTS. Shift D's row is produced inside the fault branch, immediately before break@shifts, and that jump leaves the shift loop entirely -- skipping the bookkeeping that sits after the inner loop on the normal path. D is never tallied, its four runs never join tRuns, its 450 cwt never joins tLoaded, and its two unfinished runs never join tLeft. So the board shows a shift whose numbers appear in no total, and every reconciliation line still prints agree: true, because the omission is consistent: the accumulators all skipped D together, so they still balance against each other. This is the analogy's failure exactly -- a valid signal that names a destination past the work that had to happen. The fix is structural: the row print and the accumulator updates belong on one path that every exit passes through. Two smaller limits. D's LEFT of 2 lumps run 2, started and abandoned mid-weighing, together with run 3, never touched, and those are not the same event. And tEmpty is incremented as tubs are weighed, before a run's fate is known, so an empty tub in a run that is later refused would be counted in a figure whose companion weight was discarded; that does not bite on this log only because both empty tubs happen to sit in runs that were taken, which is luck rather than design.
Common Mistakes
- Using a bare
breakfor a nested search. It leaves the inner loop and the outer loop carries on to its next pass, so the search keeps running and the answer keeps being overwritten. You get the last match instead of the first, after scanning everything, and both the value and the timing look plausible enough to survive review.
- Getting the label syntax backwards. The declaration is
outer@ for (...)with the@after the name; the reference isbreak@outerwith the@before it.break outerand@outer breakare both nonsense, and the asymmetry catches everyone once.
- Trying to
breakorcontinueinside aforEach. A lambda body is not a loop body, so there is no loop for the jump to name and it will not compile. Use a realforloop, or the function that already means what you want:firstOrNull,any,none,indexOfFirstandtakeWhilecover most break-shaped searches without a jump at all.
- Writing
returnwhen you meantreturn@forEach. Inside an inlined lambda the bare form abandons the entire enclosing function, returning whatever it had accumulated so far. The compiler cannot warn you, because both forms are legal and both are sometimes right.
- Expecting a non-local
returnfrom a lambda that cannot support one. A barereturnin a lambda needs the receiving function to beinline, because it needs a real frame in the caller to return from. With a non-inline function, or anoinlineorcrossinlineparameter, the code stops compiling --crossinlineexists to forbid it, since the lambda may run after the caller's frame is gone.
- Believing
repeat(n)is a loop. It is an inline function taking a lambda, sobreakandcontinueare unavailable.return@repeatgives you thecontinuesense and there is nobreaksense at all; if you need to stop early, writefor (i in 0 until n).
- Jumping out past bookkeeping that had to run. Anything after a loop -- printing a row, updating a total, releasing a lock -- is skipped by a
breaknaming an outer loop, because that jump lands after the outer loop, not the inner one. The result balances internally and undercounts silently.
- Mixing the two kinds of label.
breakandcontinueaccept only loop labels;returnaccepts only lambda and function labels.break@myLambdaandreturn@myLoopare both compile errors, and the diagnostics talk about the label rather than the mismatch, so they read as though it were misspelt.
- Naming the wrong loop in a three-deep nest.
break@outerwhen you meant the middle loop compiles, runs, and discards two levels of pending work instead of one. Nothing marks the mistake, because every label in scope is equally spellable.
Best Practices
- Prefer extracting a nested search into its own function and returning from it. A plain
returnleaves every level at once, needs no label, cannot name the wrong loop, and gives the search a name that says what it looks for.
- Name a label after what its loop iterates --
shifts@,perRun@,rows@-- and neverouter@orloop1@. A jump readingbreak@shiftstells you what is being abandoned;break@outeronly tells you which of two nests it is.
- Delete a label that nothing jumps to. A labelled loop is a signal to the reader that somewhere inside it a non-local jump exists, and sending that signal for nothing costs them a search of the whole body.
- Route every exit from a loop nest through one place that does the bookkeeping. Never duplicate a row print or a total update into an early-exit branch -- set a status variable, break to the single exit, and let one block handle every case.
- Reach for the collection function before the label.
firstOrNull,indexOfFirst,any,none,takeWhileandfindcover most break-shaped searches, and a search expressed as a value cannot leak a half-updated accumulator the way a jump can.
- Write
return@forEachonly where thecontinuesense is genuinely wanted, and consider a guard clause orfilterinstead. It reads like a return and behaves like a continue, which is the one place in Kotlin where the word and the effect disagree.
- Never give a label the same name as a variable or function in scope. Labels have their own namespace so the compiler will accept it, but
break@countnext to aval countreads as though a value were being returned.
- Keep loop nesting to two levels. Once a third level needs to jump to the first, the middle level is a function waiting to be extracted, and extracting it usually replaces both labels with one
return.
Practice Exercises
- Fix the
bare breakloop from the first example three ways: with a label, by extracting the search into a function that returns on the first match, and with a nestedindexOfFirst. Print the tub location and the number of weights inspected for each, and confirm all three report level 0 tub 2 after exactly 3 checks.
- Repair the totals bug in the shift log. Restructure
mainso the fault branch sets a status and leaves the run loop, and so the row print and every accumulator update happen once per shift on a single path. Add a line asserting that rows printed equals shifts tallied, and show it printingtruewhere the original would printfalse.
- Write
fun firstOverload(shifts: List<List<Int>>, safe: Int): Stringreturning the first run oversafeas"shift i run j", using nestedforEachIndexedand a non-localreturn. Write it again with a labelledfornest, and a third time withindexOfFirst. Compare all three when no run is over the limit.
- Demonstrate the difference between
returnandreturn@forEach. Write one function that sums a list but bails out on the first negative number with an unlabelledreturn, and one that skips negatives withreturn@forEach. Run both overlistOf(10, -3, 20, -1, 30)and print each result with the count of elements it actually visited.