Coding for All
Lesson 22: Continue
Continue Skip one trip around a loop with continue.
1fun main() {
2 var counter = 0
3 while (counter < 5) {
4 counter++
5 if (counter == 3) {
6 continue
7 }
8 println(counter)
9 }
10}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
1
2
4
5
Every line, explained
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
var counter = 0
var creates a variable whose value CAN change later. The Kotlin habit is: use val unless you know the value must change.
while (counter < 5) {
A while loop repeats its block for as long as the condition in the round brackets is true. The condition is checked again before every trip around the loop. This loop runs while counter is less than 5.
counter++
index++ increases index by 1. It is a short way of writing index = index + 1 (you can also write index += 1).
if (counter == 3) {
if checks the condition inside its round brackets. If the condition is true, Kotlin runs the code between { and }. If it is false, Kotlin skips that code completely. We single out the moment the counter hits 3.
continue
continue skips the rest of this trip around the loop and jumps straight back to the condition check. When counter is 3, the println below is skipped, so 3 never appears in the output.
}
This } closes the if block.
println(counter)
println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Prints 1, 2, 4 and 5, but not 3, because continue skipped past this line that time.
}
This } closes the while loop.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.