Kotlin For Loop
Kotlin's for loop iterates over anything that can be iterated: ranges of numbers, arrays, lists, strings, maps… There is no C-style for (int i = 0; i < n; i++) — ranges cover that case more readably.
Looping over a collection
fun main() {
val planets = listOf("Mercury", "Venus", "Earth")
for (planet in planets) {
println("Hello, $planet!")
}
}Hello, Mercury!
Hello, Venus!
Hello, Earth!
Read it as "for each planet in planets". The loop variable is a fresh read-only value on each iteration.
Looping over numbers
fun main() {
for (i in 1..5) print("$i ")
println()
for (i in 0..<5) print("$i ") // 5 excluded
println()
for (i in 10 downTo 0 step 2) print("$i ")
println()
}1 2 3 4 5
0 1 2 3 4
10 8 6 4 2 0
| Expression | Values |
|---|---|
1..5 |
1, 2, 3, 4, 5 (inclusive) |
0..<5 |
0, 1, 2, 3, 4 (end excluded) |
5 downTo 1 |
5, 4, 3, 2, 1 |
0..10 step 3 |
0, 3, 6, 9 |
Ranges are explained in detail in the next chapter.
Index and value together
When you need the position as well as the element, use indices or — even nicer — withIndex() with destructuring:
fun main() {
val podium = listOf("Ada", "Linus", "Grace")
for (i in podium.indices) {
println("${i + 1}. ${podium[i]}")
}
for ((index, name) in podium.withIndex()) {
println("Index $index -> $name")
}
}1. Ada
2. Linus
3. Grace
Index 0 -> Ada
Index 1 -> Linus
Index 2 -> Grace
Strings and maps
A string iterates over its characters; a map iterates over entries, which you can destructure into key and value:
fun main() {
for (c in "abc") print(c.uppercaseChar())
println()
val stock = mapOf("apples" to 12, "pears" to 0, "kiwis" to 7)
for ((fruit, count) in stock) {
val status = if (count > 0) "$count left" else "sold out"
println("$fruit: $status")
}
}ABC
apples: 12 left
pears: sold out
kiwis: 7 left
Nested loops
A loop inside a loop runs the inner loop completely for each step of the outer one — perfect for tables:
fun main() {
for (row in 1..3) {
for (col in 1..4) {
print("${(row * col).toString().padStart(3)}")
}
println()
}
} 1 2 3 4
2 4 6 8
3 6 9 12
repeat and forEach
Two handy alternatives from the standard library:
repeat(3) { println("Hip hip hooray!") } // run a block n times
listOf("a", "b").forEach { println(it) } // lambda for each elementTip: Prefer
for (x in items)orforEachover manual index juggling. Fewer indices means fewer off-by-one bugs.
Test yourself
Which values does for (i in 0..<3) produce?
- 0, 1, 2, 3
- 0, 1, 2
- 1, 2, 3
- 1, 2
How do you loop from 10 down to 1?
- for (i in 10..1)
- for (i in 10 downTo 1)
- for (i in 1..10 reversed)
- for (i = 10; i > 0; i--)
What does withIndex() give you in a for loop?
- Only indices
- Pairs of index and value
- A sorted list
- The size