Kotlin — Loop control with for and break
A Kotlin for loop takes successive values from a range or collection. continue skips the remainder of one pass and break leaves the loop.
A simple example
Print the numbers 1 to 3
- Start with Start at 1
- Do this Visit 1, 2, 3
- Result 1 → 2 → 3
fun main() {
for (n in 1..3) {
println(n)
}
}
1 2 3
Stop at the end of a batch
The list holds Int values and the for loop visits them in order. Use var for the changing total. The zero test ends the loop before the last reading can be added.
A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.
Run the example
Kotlin/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 total = 0
for (reading in listOf(4, -1, 0, 7)) {
if (reading == 0) break
if (reading < 0) continue
total += reading
}
println(total)
}
4
Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.
Try it yourself
What changes if the input is 4, −1, 7, 0?
Check your answer
Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.