In Kotlin, break
and continue
are powerful control flow statements used within loops. They help developers manage loop execution more effectively, enhancing code readability and efficiency.
The break
statement is used to exit a loop prematurely. When encountered, it immediately terminates the innermost enclosing loop.
for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}
// Output: 1, 2, 3, 4
In this example, the loop prints numbers from 1 to 4 and then exits when i
equals 5.
The continue
statement skips the rest of the current iteration and moves to the next iteration of the loop.
var i = 0
while (i < 5) {
i++
if (i == 3) {
continue
}
println(i)
}
// Output: 1, 2, 4, 5
Here, the loop skips printing 3 but continues with the next iterations.
Kotlin allows the use of labels with break
and continue
statements. This is particularly useful in nested loops.
outerLoop@ for (i in 1..3) {
for (j in 1..3) {
if (i == 2 && j == 2) {
break@outerLoop
}
println("$i, $j")
}
}
This code will break out of both loops when i
is 2 and j
is 2.
break
and continue
judiciously to avoid making your code hard to follow.To further enhance your understanding of Kotlin control flow, explore these related topics:
Mastering break
and continue
statements will significantly improve your ability to write efficient and readable Kotlin code, especially when dealing with complex loop structures.