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) // 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.