Kotlin break and continue
Inside a loop, you sometimes need to stop the loop early or skip one iteration. Kotlin gives you two tools: break exits the loop completely, and continue skips only the current round and moves to the next.
break — Exit the Loop Early
for (i in 1..10) {
if (i == 6) break
println(i)
}Output:
1
2
3
4
5The loop stops completely when i reaches 6. Numbers 6 through 10 are never printed.
continue — Skip One Iteration
for (i in 1..10) {
if (i % 2 == 0) continue // skip even numbers
println(i)
}Output:
1
3
5
7
9Each even number triggers continue, which jumps straight to the next value of i. The println line is skipped for those values.
Diagram: break vs continue
i = 1 → print 1
i = 2 → even → continue → jump to i = 3
i = 3 → print 3
i = 4 → even → continue → jump to i = 5
i = 5 → print 5
i = 6 → if break: STOP LOOP ENTIRELY
if continue: jump to i = 7
break in a while Loop
var balance = 1000
var day = 0
while (true) {
day++
balance -= 150 // spend 150 per day
if (balance <= 0) {
println("Money ran out on day $day")
break
}
}
// Output: Money ran out on day 7Labeled break — Escape Nested Loops
By default, break exits only the innermost loop. Use a label to break out of an outer loop:
outer@ for (row in 1..4) {
for (col in 1..4) {
if (row == 2 && col == 3) {
println("Breaking at row=$row, col=$col")
break@outer // exits both loops
}
print("($row,$col) ")
}
println()
}Output:
(1,1) (1,2) (1,3) (1,4)
(2,1) (2,2) Breaking at row=2, col=3Labeled continue — Skip in Outer Loop
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) continue@outer // skip rest of outer loop iteration
println("i=$i, j=$j")
}
}Output:
i=1, j=1
i=2, j=1
i=3, j=1When j equals 2, continue@outer skips the rest of the inner loop and jumps to the next i value immediately.
Practical Example: Find First Prime
fun main() {
var found = false
outer@ for (num in 2..100) {
for (divisor in 2 until num) {
if (num % divisor == 0) continue@outer // not prime, try next num
}
println("First prime found: $num")
found = true
break // stop after finding the first prime
}
}Output:
First prime found: 2