How to Use Continue in Kotlin: Simple Guide with Examples
continue statement is used inside loops to skip the current iteration and move to the next one immediately. It helps control loop flow by ignoring the remaining code in the loop body for that iteration.Syntax
The continue statement is used inside loops like for, while, or do-while. When Kotlin encounters continue, it skips the rest of the current loop iteration and jumps to the next one.
Optionally, you can use a label with continue to specify which outer loop to continue when nested loops are involved.
for (i in 1..5) { if (i == 3) continue println(i) } // Using label with continue outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) continue@outer println("i = $i, j = $j") } }
Example
This example shows how continue skips printing the number 3 in a loop from 1 to 5. It also demonstrates using a label to skip to the next iteration of an outer loop when a condition in the inner loop is met.
fun main() {
for (number in 1..5) {
if (number == 3) {
continue // Skip number 3
}
println("Number: $number")
}
println("--- Nested loops with label ---")
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
continue@outer // Skip to next i when j is 2
}
println("i = $i, j = $j")
}
}
}Common Pitfalls
A common mistake is using continue outside of loops, which causes a compilation error because continue only works inside loops. Another pitfall is forgetting to use labels in nested loops, which can lead to unexpected behavior by continuing the wrong loop.
Also, overusing continue can make code harder to read, so use it sparingly for clarity.
fun main() {
// Wrong: continue outside loop
// continue // This will cause a compile error
// Nested loops without label
for (i in 1..2) {
for (j in 1..2) {
if (j == 2) {
continue // Only continues inner loop
}
println("i=$i, j=$j")
}
}
println("--- Correct with label ---")
outer@ for (i in 1..2) {
for (j in 1..2) {
if (j == 2) {
continue@outer // Correctly continues outer loop
}
println("i=$i, j=$j")
}
}
}Quick Reference
| Usage | Description |
|---|---|
| continue | Skips the rest of the current loop iteration and moves to the next iteration. |
| continue@label | Skips to the next iteration of the loop marked by the specified label. |
| Allowed loops | for, while, do-while |
| Not allowed | Outside loops (causes compile error) |
Key Takeaways
continue inside loops to skip the current iteration and proceed to the next.continue@label to specify which loop to continue.continue outside loops; it will cause a compile error.continue can reduce code readability, so use it carefully.continue only skips the rest of the current iteration, not the entire loop.