Kotlin — Continue statements
Kotlin continue moves on to the next loop iteration. Put a rejection test before changes that should apply only to accepted records.
A simple example
Skip just the number 2
- Start with Visit 1 through 3
- Do this Skip 2
- Result 1 → 3
fun main() {
for (n in 1..3) {
if (n == 2) {
continue
}
println(n)
}
}
1 3
Exclude invalid readings while keeping zero
Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. Loop control belongs to this for statement. With higher-order operations such as forEach, labeled local returns have their own rules.
A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.
Run the example
Use Kotlin 2.2 on the JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
var count = 0
var sum = 0
for (reading in listOf(-2, 0, 4, -1, 6)) {
if (reading < 0) continue
count++
sum += reading
}
println("$count readings, sum $sum")
}
3 readings, sum 10
The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.
Try it yourself
Append −3 and then 0. What should the count and sum become?
Check your answer
The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.