Kotlin Break and Continue
Sometimes you need to change a loop's normal flow: stop early once you've found what you were looking for, or skip a single item. Kotlin provides break and continue for this — plus labels for nested loops.
| Keyword | Effect |
|---|---|
break |
leaves the loop immediately |
continue |
skips the rest of this iteration and jumps to the next one |
break
fun main() {
val readings = listOf(12, 18, 25, 41, 30, 22)
for (r in readings) {
if (r > 40) {
println("Alarm! Reading $r is too high, stopping.")
break
}
println("Reading $r OK")
}
}Reading 12 OK
Reading 18 OK
Reading 25 OK
Alarm! Reading 41 is too high, stopping.
Readings after 41 are never looked at.
continue
fun main() {
for (i in 1..10) {
if (i % 3 == 0) continue // skip multiples of 3
print("$i ")
}
println()
}1 2 4 5 7 8 10
continue is a good way to filter out items you don't want to process, keeping the main logic un-indented.
break and continue in while loops
Both keywords work the same way in while and do..while. A common pattern is while (true) with a break when a goal is reached:
fun main() {
var n = 1
while (true) {
n *= 2
if (n == 16) continue
if (n > 100) break
println(n)
}
println("Stopped at $n")
}2
4
8
32
64
Stopped at 128
Labels for nested loops
A plain break only leaves the innermost loop. To break out of an outer loop, give it a label — any name followed by @ — and write break@label:
fun main() {
val grid = listOf(
listOf(3, 8, 1),
listOf(9, 4, 7),
listOf(2, 6, 5)
)
val target = 4
search@ for (row in grid.indices) {
for (col in grid[row].indices) {
if (grid[row][col] == target) {
println("Found $target at row $row, column $col")
break@search
}
}
}
println("Search finished")
}Found 4 at row 1, column 1
Search finished
continue@label works the same way: it jumps to the next iteration of the labelled loop.
fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) continue@outer
println("i=$i j=$j")
}
}
}i=1 j=1
i=2 j=1
i=3 j=1
Stopping a forEach
Inside a lambda such as forEach { … }, break and continue aren't allowed. Use return@forEach to skip to the next element (like continue). If you need to stop entirely, use a normal for loop instead.
listOf(1, 2, 3, 4).forEach {
if (it == 2) return@forEach // skips 2
println(it)
}Tip: Often you don't need
breakat all — functions likefirst { … },any { … }ortakeWhile { … }express "search until found" more clearly. You'll meet them in Collection Operations.
Test yourself
What does continue do?
- Exits the loop
- Skips the rest of the current iteration
- Restarts the loop from the beginning
- Pauses the program
How do you exit an outer loop from inside an inner loop?
- break break
- break@label with a labelled outer loop
- exit()
- return@inner
What is printed? for (i in 1..5) { if (i == 3) break; print(i) }
- 12
- 123
- 1245
- 12345