Skip to the workspace
Pebellslearn by building
Conditional Expressions and Loops  ›  Capstone Project

break, continue and Labels

break & continue 15 minbreak leaves the innermost loop, continue skips to its next round, and a label such as outer@ lets either one target an enclosing loop instead.

kotlin / break, continue and Labels

Explore each scene at your own pace.

01 · The rule

The rule

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 free
  • break ends the innermost loop immediately. Code after the loop carries on.
  • continue abandons the rest of the current round and jumps to the next one. In a while loop, 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 1

A 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.