Skip to the workspace
Pebellslearn by building
Conditional Expressions and Loops  ›  Lesson

for Loops

for 12 minKotlin's for loop walks through anything that provides an iterator, such as a range, a collection or a map, rather than counting with an index and a condition.

kotlin / for Loops

Explore each scene at your own pace.

01 · The rule

The rule

for Loops

Kotlin's for loop walks through anything that provides an iterator, such as a range, a collection or a map, rather than counting with an index and a condition.

Iterate over values, indexes or pairs without confusing their roles.

Printing the café menu means doing the same thing for every drink. Writing one println per drink breaks the day the menu changes. A loop repeats the work once per item, however many items there are.

The rule

for walks through things; it does not count by itself.

Kotlin's for takes each element of something iterable, one at a time:

val drinks = listOf("latte", "mocha", "chai")
for (drink in drinks) {
    println(drink)
}

There is no C-style loop like for (i = 0; i < 3; i++). When you need numbers, walk through a range:

for (i in 1..3) print(i)            // 123
for (i in 0 until drinks.size) println(drinks[i])
for (i in drinks.indices) println(drinks[i])   // same, safer
for (i in 10 downTo 0 step 5) print("$i ") // 10 5 0

drinks.indices is the range 0..size - 1, so it can never step off the end.

When you want both the position and the item, use withIndex() and unpack the pair:

for ((i, drink) in drinks.withIndex()) {
    println("${i + 1}. $drink")      // 1. latte, 2. mocha, 3. chai
}

Maps unpack into key and value:

val prices = mapOf("latte" to 3.5, "mocha" to 4.0)
for ((drink, price) in prices) {
    println("$drink costs $price")
}

The loop variable (drink, i) is read-only and exists only inside the loop. For "just do this n times" without needing the number, repeat(3) { println("Brewing…") } is a tidy alternative.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.