Ranges

Creating Ranges

Example

A range is a sequence of values from a start to an end. .. includes the end; until (or ..<) excludes it.

fun main() {
    println((1..5).toList())
    println((1 until 5).toList())
    println((1..<5).toList())
    println((10 downTo 1).toList())
    println((0..20 step 5).toList())
    println(('a'..'e').toList())
}

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 4]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[0, 5, 10, 15, 20]
[a, b, c, d, e]

Range Functions

Example

Ranges are objects with useful properties and functions.

fun main() {
    val r = 1..10
    println(r.first)
    println(r.last)
    println(r.count())
    println(r.sum())
    println(5 in r)
    println(15 in r)
    println((5..1).isEmpty())   // empty: use downTo to count down
}

Output

1
10
10
55
true
false
true

Range Cheat Sheet

ExpressionValues
1..51, 2, 3, 4, 5
1 until 5 / 1..<51, 2, 3, 4
5 downTo 15, 4, 3, 2, 1
1..10 step 31, 4, 7, 10
10 downTo 0 step 510, 5, 0
'a'..'d'a, b, c, d