Break And Continue in Kotlin
📌 Break and Continue in Kotlin
In Kotlin, break and continue are control flow statements that are used to manage the execution of loops. They allow you to skip or exit from loops based on certain conditions.
✅ 1. break Statement
The
breakstatement is used to exit a loop immediately when a specified condition is met.It is often used inside
for,while, ordo-whileloops.
📌 Example: Using break
.10) { if (i == 5) { println("Breaking at $i") for (i in 1..10) { if (i % 2 == 0) { println("Skipping $i") Odd number: 1Skipping 2Odd number: 3Skipping 4Odd number: 5Skipping 6Odd number: 7Skipping 8Odd number: 9Skipping 10
✅ 3. Using break and continue with Labels
Kotlin provides labels to break or continue from nested loops using @labelName.
break@labelName→ Exits the specified labeled loop.continue@labelName→ Skips the current iteration of the labeled loop.
📌 Example: Using Labels with break
outer@ for (i in 1..3) { for (j in 1..3) { if (i == 2 && j == 2) { println("Breaking outer loop at i=$i, j=@outer } println("i=$i, j=outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) { println("Continuing outer loop at i=$i, j=@outer } println("i=$i, j=$j") }}
Output:
i=1, j=1Continuing outer loop at i=1, j=2i=2, j=1Continuing outer loop at i=2, j=2i=3, j=1Continuing outer loop at i=3, j=2
✅ Conclusion
Use
breakto exit a loop early when a condition is met.Use
continueto skip the current iteration and move to the next one.Labels are useful for controlling nested loops with
breakandcontinue.