Careeroza
break, continue and Labels
break and continue
Example
break leaves the loop. continue skips to the next step.
fun main() {
for (i in 1..10) {
if (i % 2 == 0) continue // skip even numbers
if (i > 7) break // stop after 7
print("$i ")
}
println()
}Output
1 3 5 7
Labels for Nested Loops
Example
A label like outer@ lets break@outer exit the outer loop directly.
fun main() {
val seats = listOf(
listOf("A1", "A2", "A3"),
listOf("B1", "B2", "B3"),
)
val wanted = "B2"
outer@ for (row in seats) {
for (seat in row) {
println("Checking $seat")
if (seat == wanted) {
println("Found $wanted")
break@outer
}
}
}
}Output
Checking A1 Checking A2 Checking A3 Checking B1 Checking B2 Found B2