Kotlin Break and Continue
The break and continue keywords give you fine-grained control over loop execution, and Kotlin extends them with labels for handling nested loops precisely.
Using break to Exit a Loop
The break keyword immediately terminates the nearest enclosing loop, skipping any remaining iterations. Execution resumes with the first statement after the loop.
break in a loop
fun main() {
for (i in 1..10) {
if (i == 5) {
break
}
println("i = $i")
}
println("Loop finished")
}Using continue to Skip an Iteration
The continue keyword skips the rest of the current iteration and jumps straight to the loop's next check, without exiting the loop entirely. This is handy for filtering out values you don't want to process.
continue in a loop
fun main() {
for (i in 1..10) {
if (i % 2 != 0) {
continue
}
println("Even number: $i")
}
}Labeled break and continue
When loops are nested, a plain break or continue only affects the innermost loop. Kotlin lets you label an outer loop with an identifier followed by @, then reference that label to break or continue the outer loop directly from inside the nested one.
- A label is written as identifier@ directly before the loop keyword, e.g. outer@ for (...).
- break@label exits the labeled loop entirely.
- continue@label skips to the next iteration of the labeled loop, not the innermost one.
Labeled break
fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
break@outer
}
println("i=$i, j=$j")
}
}
println("Done")
}Exercise: Kotlin Break and Continue
What does the break statement do when it runs inside a loop?