Coding for All
Lesson 19: For Loop Booleans
For Loop Booleans Combine a loop with an if statement.
1fun main() {
2 val flags = booleanArrayOf(true, true, false)
3 for ((index, flag) in flags.withIndex()) {
4 if (flag) {
5 println("flags[$index] is true")
6 }
7 }
8}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
flags[0] is true
flags[1] is true
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.
val flags = booleanArrayOf(true, true, false)
A boolean array of true/false values.
for ((index, flag) in flags.withIndex()) {
flags.withIndex() hands you BOTH the position and the item on every trip. The (index, flag) part unpacks those two into their own names: index is 0, 1, 2 and flag is the value at that position.
if (flag) {
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. The condition is flag, whichever boolean the loop is currently visiting.
println("flags[$index] is true")
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. The string template drops the number index into the text, so "flags[$index] is true" becomes flags[0] is true.
}
This } closes the if block.
}
This } closes the for loop. Everything between the loop's { and } is repeated on every trip around the loop.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.