In this tutorial you will learn about the Kotlin continue and its application with practical example.
Kotlin continue statement
The continue statement gives you way to skip over the current iteration of any loop. When a continue statement is encountered in the loop, the kotlin interpreter ignores rest of statements in the loop body for current iteration and returns the program execution to the very first statement in the loop body. It does not terminates the loop rather continues with the next iteration.
Syntax:-
1 2 3 4 5 6 7 8 |
while (condition1) { // loop body if (condition2) { continue } // loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main(args: Array<String>) { for (ctr in 1..10) { if (ctr == 5) { println("5 is skipped") continue println("This won't be printed too.") } println("Number is $ctr") } println("Out of loop") } |
Output:-
1 2 3 4 5 6 7 8 9 10 11 |
Number is 1 Number is 2 Number is 3 Number is 4 5 is skipped Number is 6 Number is 7 Number is 8 Number is 9 Number is 10 Out of loop |
As you can see when ctr == 5, continue statement is executed which causes the current iteration to end and the control moves on to the next iteration.
Kotlin Labeled continue
The standard unlabeled continue statement is used to skip the current iteration of nearest enclosing loop. In Kotlin, there is another form of continue (labeled continue ) statement is used to skip iteration of specified loop (can be outer loop). In Kotlin, Label is an identifier which is followed by @ sign, for example abc@, test@.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main(args: Array<String>) { outerfor@ for (i in 1..3) { for (j in 1..3) { println("i = $i and j = $j") if (i == 2) { println("I am Skipped") continue@outerfor } println("I am Printed") } } } |
Output:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
i = 1 and j = 1 I am Printed i = 1 and j = 2 I am Printed i = 1 and j = 3 I am Printed i = 2 and j = 1 I am Skipped i = 3 and j = 1 I am Printed i = 3 and j = 2 I am Printed i = 3 and j = 3 I am Printed |
Here, when i == 2 expression is evaluated to true, continue@outerfor is executed which skips the current iteration of the enclosed loop and return control to the loop marked with label outerfor@.