Part 04 / Topic 5 of 8
for loops
for (x in ...) walks a range, a progression or a collection, running its body once per value, with
no counter to manage by hand.
for (seat in 1..5) {
println("Boarding seat $seat")
}
val cities = listOf("Mumbai", "Pune", "Nashik")
for (city in cities) {
println("Stop: $city")
}
Boarding seat 1
Boarding seat 2
Boarding seat 3
Boarding seat 4
Boarding seat 5
Stop: Mumbai
Stop: Pune
Stop: Nashik
When you need the position as well as the value, withIndex() pairs them up — no separate counter
variable to keep in sync by hand:
for ((index, city) in cities.withIndex()) {
println("${index + 1}. $city")
}
1. Mumbai
2. Pune
3. Nashik
A for also walks a stepped, descending progression directly, same as any other range:
for (floor in 10 downTo 2 step 2) {
println("Floor $floor: checking fire exit")
}
Floor 10: checking fire exit
Floor 8: checking fire exit
Floor 6: checking fire exit
Floor 4: checking fire exit
Floor 2: checking fire exit
Unlike if/when, for is never an expression — it only ever runs its body for its side effects
(println, updating a var outside the loop, and so on) and produces no value of its own.
Full program: examples/05_for_loops.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.