Ranges (Kotlin)

A range is a sequence of values between a start and end, created with operators like 1..10 (inclusive). Ranges support iteration, membership tests with in, and stepping or counting down.

Kotlin

The .. operator builds an inclusive range: 1..5 is 1, 2, 3, 4, 5. Use until or ..< for an exclusive upper bound (1 until 5 stops at 4), downTo to count backwards (5 downTo 1), and step to skip values (1..10 step 2).

Ranges are commonly used in for loops (for (i in 1..3)) and in conditions with in / !in to test membership (if (x in 1..100)). They also slot neatly into when branches: in 1..9 -> "small".

Ranges work for any Comparable, not just Int — 'a'..'z' is a character range. Integer ranges are also iterable as a cheap, allocation-light progression, making them the idiomatic counting construct in Kotlin.

Syntax

for (i in 1..5) { ... }
if (x in 0..100) { ... }

Examples

Kotlin

val result = StringBuilder()
for (i in 1..10 step 3) result.append("$i ")
println(result.toString().trim())
println(7 in 1..10)

Output:

1 4 7 10
true

Learn it in a lesson

See also

Back to the Dictionary