In this tutorial, you shall learn about continue statement in Kotlin, and how to use continue statement in loops, with examples.
Kotlin continue statement
Kotlin continue statement is used to proceed to the next iteration of the enclosing loop, be it While loop, Do-while loop, or For loop.
By default, Kotlin continue statement proceeds with the next iteration of the nearest enclosing loop, but we can specify, via label, which enclosing loop must be continued with next iteration.
Syntax
The syntax to use a continue statement is given below.
continue
//or
continue@label_name
- continue: a Koltin keyword.
- label_name: a label assigned to an enclosing loop. You may specify your own label name in place of this.
Examples
The following examples, we will see how to continue with different loop statements using continue statement.
1. Continue in For Loop
In the following program, we take a For loop to print numbers from one to ten. Also, we write a conditional If-statement inside the loop to continue the loop with next iteration if the number is five.
Main.kt
fun main() {
for (i in 1..10) {
if (i==5) continue
println(i)
}
}
Output
1
2
3
4
6
7
8
9
10
2. Continue in While Loop
In the following program, we take a While loop to print numbers from one to five. Also, we write a conditional If-statement inside the loop to continue with next iteration if the number is three.
Main.kt
fun main() {
var i = 0
while(i < 5) {
i++
if (i==3) continue
println(i)
}
}
Output
1
2
4
5
3. Continue in Do-while Loop
In the following program, we take a Do-while loop to print numbers from one to five. Also, we write a conditional If-statement inside the loop to continue with next iteration if the number is three.
Main.kt
fun main() {
var i = 0
do {
i++
if (i==3) continue
println(i)
} while(i < 5)
}
Output
1
2
4
5
4. Continue in specific loop identified by label
In the following program, we take a While loop inside a For loop to print some star pattern, and we continue with the next iteration of outer loop labeled with the name loop1, using continue statement when a condition is met.
Main.kt
fun main() {
loop1@ for(i in 1..10) {
var k = 0
while (k < i) {
print("*")
k++
if (i*k > 50) {
println()
continue@loop1
}
}
println()
}
}
Output
*
**
***
****
*****
******
*******
*******
******
******
Conclusion
In this Kotlin Tutorial, we learned how to use continue statement to proceed with the next iteration of a loop.