Loops
8 min · Kotlin
Repeat work without writing it out a hundred times.
Enemy 1 of 5
Loops let you repeat a block of code without copying and pasting it. Kotlin's for loop is designed to walk over a range of values: for (i in 0..2) runs its body three times, with i taking the values 0, then 1, then 2 in turn.
The 0..2 syntax is Kotlin's range operator, and — unlike Rust's 0..3 or Python's range(3) — it's inclusive on both ends by default: 0..2 means 0, 1, and 2, including the final value. If you want a range that excludes the end (matching how many other languages default), Kotlin provides until: 0 until 3 gives you 0, 1, 2, the same three values as Rust's 0..3. Mixing these two conventions up across languages is a very common source of off-by-one bugs, so it's worth pausing on this the first time you switch languages.
Compared to the classic C-style for (int i = 0; i < 3; i++) loop, Kotlin's for (i in 0..2) is shorter and removes the chance of writing an inconsistent condition or increment — the range fully describes what values i will take.
Loading editor...