break, continue and Labels
A customer walks in and asks for a table. You scan the café floor row by row, table by table. The moment you see a free one, you stop looking. And if a whole row is roped off for cleaning, you skip it without checking a single table. Loops need the same two moves.
The rule
break leaves the loop; continue skips this round; a label picks which loop.
val tables = listOf("taken", "taken", "free", "free")
for ((i, t) in tables.withIndex()) {
if (t == "taken") continue // skip to the next table
println("Table $i is free")
break // stop searching
}
// prints: Table 2 is freebreakends the innermost loop immediately. Code after the loop carries on.continueabandons the rest of the current round and jumps to the next one. In awhileloop, that means back to the condition.
With nested loops, both words affect only the innermost loop. To reach an outer loop, give it a label: a name followed by @, placed before the loop. Then write break@name or continue@name.
val floor = listOf(
listOf("taken", "taken"),
listOf("taken", "free"),
listOf("free", "free")
)
rows@ for ((r, row) in floor.withIndex()) {
for ((c, t) in row.withIndex()) {
if (t == "free") {
println("Seat at row $r, table $c")
break@rows // leave both loops
}
}
}
// prints: Seat at row 1, table 1A plain break there would leave only the inner loop. The outer loop would move on to row 2 and print another seat.
continue@rows would abandon the current row and jump to the next one, which is how you skip a closed row from inside the inner loop.
The shortcut
At every break or continue, draw an arrow to the loop it belongs to: the nearest enclosing loop, unless a label names another. break lands just after that loop; continue lands at its next round.
Row 0
Both tables are taken. The inner loop ends normally; the outer moves on.
Labels can make code harder to follow. If you need them often, moving the search into its own function and using return is usually clearer.
Drills
Answer fast — trust the rule.
What does for (i in 1..5) { if (i == 3) break; print(i) } print?
What does for (i in 1..5) { if (i == 3) continue; print(i) } print?
Inside two nested loops, a plain break in the inner loop does what?
Which line correctly labels a loop and later leaves it?
outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) continue@outer; print("[$i$j]") } }. What is printed?
Remember
breakleaves the loop;continuejumps to its next round.- Both target the innermost loop unless a label (
name@) says otherwise. - Draw the arrow:
breaklands after that loop,continueat its next round.
