๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Ranges

A range is a run of values from a start value to an end value. One range can name many values at once.

First, last and count

first gives the opening value and last gives the closing value. count() gives how many values the range holds.

fun main() {
    println((1..5).first)
    println((1..5).last)
    println((1..5).count())
}

Stepping by two

step 2 sets a gap of two between values. toList() collects the values so they print in order.

fun main() {
    println((1..9 step 2).toList())
}

Counting down with downTo

downTo makes values go down from the start to the end. toList() shows them in that order.

fun main() {
    println((5 downTo 1).toList())
}

Stopping before the end with until

until leaves out its end value. The values start at 0 and stop before 3.

fun main() {
    println((0 until 3).toList())
}

Example

fun main() {
    val up = 1..9 step 2
    println(up.toList())
    println((4 downTo 1).toList())
    println((0 until 2).toList())
}

Key points

  • Use .. between two values to make a range that includes both ends.
  • Use until to make a range that stops before its end.
  • Use downTo to make a range that counts down.
  • Use step to set the gap between values in a range.
  • Use .first to read the first value in a range.
  • Use .last to read the last value in a range.
  • Use .count() to count how many values a range holds.
  • Use .toList() to collect the values of a range in order.

In this example, the first range steps from 1 to 9 by two, and its values print as [1, 3, 5, 7, 9]. The second range counts down from 4 to 1. The third range starts at 0 and stops before 2, so it holds 0 and 1.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does println((1..4).toList()) print?