Part 04 / Topic 7 of 8
break, continue, and labels
continue skips the rest of the current iteration and moves to the next one; break stops the
loop entirely, right where it stands.
for (n in 1..10) {
if (n % 2 != 0) continue
println("Even: $n")
}
for (n in 1..10) {
if (n > 5) break
println("Counting: $n")
}
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5
Both default to the nearest enclosing loop — a plain break/continue inside a nested loop only
ever affects the innermost one it's directly inside:
for (row in 1..3) {
for (col in 1..3) {
if (col == 2) continue // skips col 2, but only in the inner loop -- row keeps going
println("row=$row col=$col")
}
}
row=1 col=1
row=1 col=3
row=2 col=1
row=2 col=3
row=3 col=1
row=3 col=3
A label (name@ before a loop) lets break/continue reach past the nearest loop to a named
outer one. Reach for this only when the nearest-loop default above genuinely isn't what the logic
needs — most nested loops never need one, and a label on every other loop just makes the code harder
to scan for where control actually jumps:
outer@ for (row in 1..3) {
for (col in 1..3) {
if (row == 2 && col == 2) break@outer
println("labelled row=$row col=$col")
}
}
println("Loop exited via the label")
labelled row=1 col=1
labelled row=1 col=2
labelled row=1 col=3
labelled row=2 col=1
Loop exited via the label
break@outer stopped both loops the moment row == 2 && col == 2 — notice row=2 col=2 itself
is never printed, and row=3 never starts at all. Without the label, a plain break here would only
have stopped the inner loop, and row=3's pass would still have run.
Full program: examples/07_break_continue_labels.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.