break, continue and Labels
break leaves the innermost loop, continue skips to its next round, and a label such as outer@ lets either one target an enclosing loop instead.
Trace which loop a labeled break or continue targets.
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.