Line At A Time
Lesson 21: Break
Break Escape from a loop with break.
1fun main() {
2 var counter = 0
3 while (true) {
4 println(counter)
5 counter++
6 if (counter == 5) {
7 break
8 }
9 }
10}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
0
1
2
3
4
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 (true) {
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. while (true) would repeat forever, because the condition is always true! We will need break to escape.
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 the counter: 0, 1, 2, 3, 4.
counter++
index++ increases index by 1. It is a short way of writing index = index + 1 (you can also write index += 1).
if (counter == 5) {
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. Once the counter reaches 5, it is time to stop.
break
break immediately stops the loop it is inside, jumping to the code after the loop's closing brace. Without it, this while (true) loop would run forever.
}
This } closes the if block.
}
This } closes the while loop.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.