Kotlin continue
In Kotlin, continue statement is used to skip the execution of the next statements in the loop body, and continue with the next iteration of the loop.
Syntax
The syntax of a continue statement is
continue
where
continue
is keyword.
Usually, continue statement is placed inside an if-statement, so that the continue statement is executed only when a specific condition is met.
Examples
1. Continue While loop
In the following program, we take a While loop to iterate over numbers from 1 to 10. Also, we will place a continue statement inside the loop to execute when the loop is iterating for the number 5.
Kotlin Program
fun main(args: Array<String>) {
val n = 10
var i = 1
while (i <= n) {
if (i == 5) {
i++
continue
}
println(i)
i++
}
}
Output
1
2
3
4
6
7
8
9
10
The element 5 is not printed to output, because continue statement has skipped the execution of the iteration when i==5
.
Make sure you update the counter in your While loop when using continue statement.
2. Continue For loop
In the following program, we take a For loop to iterate over a string array. When the string element equals "cherry"
, we shall continue with the next iteration of the loop using continue statement.
Kotlin Program
fun main(args: Array<String>) {
val fruits = arrayOf("apple", "banana", "cherry", "mango", "fig")
for (fruit in fruits) {
if (fruit.equals("cherry")) {
continue
}
println(fruit)
}
}
Output
apple
banana
mango
fig
The string element "cherry"
is not printed because of the continue statement.