TExcelTAD
Home › Kotlin › Kotlin Ranges

Kotlin Ranges

A range describes all values between a start and an end. Ranges are small objects — 1..1_000_000 doesn't store a million numbers — and they make loops and bounds checks short and readable.

Creating ranges

Syntax Values Notes
1..5 1, 2, 3, 4, 5 closed: end included
1..<5 1, 2, 3, 4 open-ended: end excluded
1.rangeUntil(5) 1, 2, 3, 4 same as ..<
5 downTo 1 5, 4, 3, 2, 1 descending
1..10 step 3 1, 4, 7, 10 custom step
'a'..'e' a, b, c, d, e char range
kotlin · try it yourself
fun main() {
    println((1..5).toList())
    println((1..<5).toList())
    println((5 downTo 1).toList())
    println((0..20 step 5).toList())
    println(('a'..'e').joinToString(""))
}
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[5, 4, 3, 2, 1]
[0, 5, 10, 15, 20]
abcde

Checking membership with in

in tests whether a value lies inside a range — no x >= a && x <= b needed. This works for any comparable type, including strings and doubles.

kotlin · try it yourself
fun main() {
    val age = 34
    if (age in 18..65) println("Working age")

    val letter = 'q'
    println(letter in 'a'..'z')
    println(4.2 in 0.0..5.0)
    println(100 !in 1..99)
}
Working age
true
true
true

Range properties and functions

kotlin · try it yourself
fun main() {
    val r = 3..9
    println("first=${r.first} last=${r.last}")
    println("count=${r.count()} sum=${r.sum()}")
    println(r.reversed().toList())
    println((1..10).filter { it % 2 == 0 })
    println((10..1).isEmpty())
}
first=3 last=9
count=7 sum=42
[9, 8, 7, 6, 5, 4, 3]
[2, 4, 6, 8, 10]
true

Notice the last line: 10..1 is empty because a range only goes upwards. Use downTo for descending sequences.

Ranges in when

Ranges shine in when branches:

kotlin · try it yourself
fun bmiCategory(bmi: Double) = when (bmi) {
    in 0.0..<18.5 -> "underweight"
    in 18.5..<25.0 -> "normal"
    in 25.0..<30.0 -> "overweight"
    else -> "obese"
}

fun main() {
    println(bmiCategory(17.2))
    println(bmiCategory(22.0))
    println(bmiCategory(27.9))
}
underweight
normal
overweight

Progressions and step

When you use step or downTo, you get a progression — a range with a step. The step must be positive; the direction comes from downTo:

kotlin · try it yourself
fun main() {
    for (x in 100 downTo 0 step 25) print("$x ")
    println()
    val evens = 2..10 step 2
    println("last=${evens.last} step=${evens.step}")
    println((1..10 step 4).toList())
}
100 75 50 25 0 
last=10 step=2
[1, 5, 9]

In the last line 10 isn't included because stepping by 4 from 1 gives 1, 5, 9 and the next value 13 is past the end.

Clamping values

Related helpers keep a value inside bounds:

kotlin
val volume = 130.coerceIn(0..100)        // 100
val level = (-5).coerceAtLeast(0)        // 0

Tip: 0..<list.size and list.indices are equivalent; prefer indices because it states the intent.

Test yourself

How many values are in 1..<10?

  1. 10
  2. 9
  3. 8
  4. 11

What is (5..1).toList()?

  1. [5, 4, 3, 2, 1]
  2. [1, 2, 3, 4, 5]
  3. []
  4. Compile error

Which values does 0..9 step 3 produce?

  1. 0, 3, 6, 9
  2. 3, 6, 9
  3. 0, 3, 6
  4. 0, 1, 2, 3