Kotlin Break and Continue Statements
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →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
The break statement is used to exit a loop prematurely. When encountered, it immediately terminates the innermost enclosing loop.
Example of Break in a For 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
The continue statement skips the rest of the current iteration and moves to the next iteration of the loop.
Example of Continue in a While 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.
Using Labels with Break and Continue
Kotlin allows the use of labels with break and continue statements. This is particularly useful in nested loops.
Example of Labeled Break
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.
Best Practices
- Use
breakandcontinuejudiciously to avoid making your code hard to follow. - Consider using Kotlin When Expression instead of multiple if-else statements with breaks.
- When using labels, choose clear and descriptive names to enhance code readability.
Related Concepts
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.