Part 04 / Topic 4 of 8
Ranges and progressions
A range is every value between two endpoints. 1..10 is an IntRange, inclusive of both ends;
1 until 10 is the same idea but excludes the end value.
val tens = 1..10
println("1..10 contains 10: ${10 in tens}") // true
println("1..10 contains 11: ${11 in tens}") // false
val upToNine = 1 until 10
println("1 until 10 contains 10: ${10 in upToNine}") // false
println("1 until 10 contains 9: ${9 in upToNine}") // true
1..10 contains 10: true
1..10 contains 11: false
1 until 10 contains 10: false
1 until 10 contains 9: true
A progression is a range with a direction and a step: downTo counts down, step skips values.
val evens = 2..20 step 2
println("Evens: $evens")
println("Evens as a list: ${evens.toList()}")
val countdown = 10 downTo 1
println("Countdown: ${countdown.toList()}")
val everyFiveDown = 20 downTo 0 step 5
println("Every 5, going down: ${everyFiveDown.toList()}")
Evens: 2..20 step 2
Evens as a list: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Countdown: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Every 5, going down: [20, 15, 10, 5, 0]
Note the first printed line: println(evens) prints 2..20 step 2, the progression's own
description, not its contents — .toList() is what actually expands it into values, and only makes
sense once you need every value at once rather than looping lazily (section 5 does that without
.toList() at all).
Ranges work on Char too, with the same in/until/downTo rules, and the in check is itself a
clean way to validate an input without an if/else chain:
println("'e' in 'a'..'z': ${'e' in 'a'..'z'}")
val otp = 823451
val validOtpRange = 100000..999999
println("$otp is a valid 6-digit OTP: ${otp in validOtpRange}")
'e' in 'a'..'z': true
823451 is a valid 6-digit OTP: true
Full program: examples/04_ranges_and_progressions.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.