Skip to the workspace
Pebellslearn by building
Collections, Ranges and Sequences  ›  Lesson

Ranges and Progressions

Ranges 12 minA range such as 1..5 includes both ends, until and ..< exclude the end, and step and downTo turn a range into a progression that counts by larger steps or backwards.

kotlin / Ranges and Progressions

Explore each scene at your own pace.

01 · The rule

The rule

Ranges and Progressions

A range such as 1..5 includes both ends, until and ..< exclude the end, and step and downTo turn a range into a progression that counts by larger steps or backwards.

Trace included endpoints, steps and reversed progressions.

The café opens at 8 and closes at 18. "Is it open at 17?" "List every second hour." "Count down the last ten minutes." All three are questions about a run of numbers, and Kotlin has a compact way to write such runs.

The rule

.. includes the end; until leaves it out; step and downTo change the stride.

val week = 1..7            // 1, 2, 3, 4, 5, 6, 7
val hours = 8 until 18     // 8 … 17
val hours2 = 8..<18        // the same, newer spelling
println(17 in hours)       // true
println(18 in hours)       // false
  • a..b is a closed range: both a and b are included.
  • a until b and a..<b stop just before b.
  • x in range tests membership; !in tests the opposite. It works on any comparable type: 'c' in 'a'..'z' is true.

When you add a stride or a direction, the range becomes a progression: a first value, a last value and a step.

for (h in 8 until 18 step 2) print("$h ")   // 8 10 12 14 16
for (s in 10 downTo 1 step 3) print("$s ") // 10 7 4 1
println((1..10 step 4).last)               // 9

Details worth knowing:

  • step must be positive. Direction comes from downTo, not a negative step.
  • The last value is the last one the stride actually lands on: 1..10 step 4 gives 1, 5, 9, so last is 9, not 10.
  • 5..1 is empty, not a countdown. A loop over it runs zero times. Use 5 downTo 1.
  • (1..5).reversed() gives the same numbers backwards.

Ranges are cheap: 1..1_000_000 stores only its ends, not a million numbers.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.