In Kotlin can I create a range that counts backwards?
Solution 1:
Use downTo as in:
for (n in 100 downTo 1) {
//
}
Solution 2:
Just as an example of an universal range function for "for":
private infix fun Int.toward(to: Int): IntProgression {
val step = if (this > to) -1 else 1
return IntProgression.fromClosedRange(this, to, step)
}
Usage:
// 0 to 100
for (i in 0 toward 100) {
// Do things
}
// 100 downTo 0
for (i in 100 toward 0) {
// Do things
}
Solution 3:
As pointed by others, the correct answer is
for (n in 100 downTo 1) {
println(n)
}
But why did Kotlin team chose 100 downTo 1
vs 100..1
?
I think that the syntax 100..1
would be bad when we try to use variables instead of literals.
If we typed
for (n in b..a)
then it wouldn't be clear what loop we wanted to use.
We may have intended to count backwards but if b
turns out to be smaller than a
, then our program would actually count upwards! That would be a source of bugs.