Loops
for iterates ranges and collections directly rather than indices, with downTo and step for counting backward — and a range is a real, storable value in Kotlin.
for over a range
Kotlin's for loop iterates over anything iterable — most often a range, written with ..:
</> main.kt
fun main() {
for (i in 1..5) {
print("$i ")
}
println()
}
Output
1 2 3 4 5
1..5 is inclusive on both ends. Use until instead of .. for an exclusive upper bound (1 until 5 stops at 4), and downTo to count backward, optionally with step to skip values:
</> main.kt
fun main() {
for (i in 10 downTo 0 step 2) {
print("$i ")
}
println()
}
Output
10 8 6 4 2 0
while and iterating collections directly
while works as in most languages, and for can iterate a collection's elements directly without indices:
</> main.kt
fun main() {
val fruits = listOf("apple", "banana", "cherry")
var i = 0
while (i < fruits.size) {
println(fruits[i])
i++
}
for (fruit in fruits) {
println(fruit.uppercase())
}
}
Output
apple banana cherry APPLE BANANA CHERRY
The for (fruit in fruits) form is what you'll actually reach for almost every time — index-based loops over collections are rare in idiomatic Kotlin.
Note: 1..5 is a Range object, not lazily generated numbers being conjured out of nowhere — it's a real value you can store in a variable, pass to a function, or check membership in with in, e.g. if (x in 1..5). Ranges are first-class values, not just loop syntax.