Ranges and 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) // falsea..bis a closed range: bothaandbare included.a until banda..<bstop just beforeb.x in rangetests membership;!intests the opposite. It works on any comparable type:'c' in 'a'..'z'istrue.
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) // 9Details worth knowing:
stepmust be positive. Direction comes fromdownTo, not a negative step.- The last value is the last one the stride actually lands on:
1..10 step 4gives 1, 5, 9, solastis 9, not 10. 5..1is empty, not a countdown. A loop over it runs zero times. Use5 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.
The shortcut
Write out the first value, then keep adding the step while you are still inside the end. For until, the end itself is outside. For downTo, subtract instead.
First value
Start at 3.
The classic trap is writing for (i in 10..1) for a countdown. It compiles, runs zero times, and prints nothing, which is hard to notice.
Drills
Answer fast — trust the rule.
How many numbers are in 1..5?
Which is true?
What does for (i in 4..1) print(i) print?
Which values does 10 downTo 0 step 4 produce?
What is (1..20 step 6).last?
Remember
..includes the end;untiland..<exclude it.stepsets the stride,downTothe direction;5..1is empty.- Expand by hand: first value, add the step, stop at the end.
