Kotlin continue

‮i.www‬giftidea.com

In Kotlin, the continue keyword is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is encountered inside a loop, the program immediately moves on to the next iteration of the loop and skips any remaining code for the current iteration.

Here's an example that demonstrates the use of the continue statement in Kotlin:

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    for (number in numbers) {
        if (number == 3) {
            continue
        }
        println(number)
    }
    println("Done")
}

In this example, the program creates an array of numbers, and then uses a for loop to iterate over the array. Inside the loop, the program checks if the current number is equal to 3, and if it is, the program uses a continue statement to skip the current iteration and move on to the next iteration. After the loop, the program prints the string "Done" to the console. The output of the program is as follows:

1
2
4
5
Done

As you can see, the loop skipped over the number 3 and did not execute the println(number) statement for that iteration.

You can also use a continue statement inside a when expression to skip the current case and move on to the next case. Here's an example:

fun main() {
    val number = 3
    val result = when (number) {
        1 -> "One"
        2 -> "Two"
        3 -> {
            println("Skipping the number!")
            continue
            "Three"
        }
        4 -> "Four"
        else -> "Other"
    }
    println(result)
}

In this example, the program uses a when expression to determine the value of the variable result based on the value of the variable number. Inside the when expression, the program checks if the value of number is equal to 3, and if it is, the program uses a continue statement to skip the current case and move on to the next case. The output of the program is as follows:

Skipping the number!
Other

As you can see, the continue statement caused the program to skip the case for the number 3 and move on to the next case. The value of result is set to "Other" because the program did not match the case for the number 3.