`for` Loops

Learn about Kotlin's `for` loops to iterate over any iterable structure, and how to build ranges for iteration.

In contrast to while loops, Kotlin’s for loops work a bit differently than you may be used to from other languages.

for Loops #

Kotlin’s for loops are different from many other languages because they’re used in the same manner as for-each loops (or for-in loops). Thus, you always give an iterable to the for loop over which it iterates:

Press + to interact
for (number in 1..5) println(number) // 1, 2, 3, 4, 5
for (number in 1 until 5) println(number) // 1, 2, 3, 4
for (number in 1..5 step 2) println(number) // 1, 3, 5
for (number in 5 downTo 1) println(number) // 5, 4, 3, 2, 1
for (number in 5 downTo 1 step 2) println(number) // 5, 3, 1
for (char in 'a'..'c') println(char) // 'a', 'b', 'c'
for (planet in planets) println(planet) // "Jupiter", "Saturn", ...
for (char in "Venus") println(char) // 'V', 'e', 'n', 'u', 's'

A few things to note here:

  • Ranges are commonly used for basic loops, e.g., 1..5.
    • There are utilities to construct more complex ranges,
...