In Kotlin can I create a range that counts backwards?

RangeKotlin

Range Problem Overview


I looked at the documentation for the Ranges and I see no mention of backwards ranges.

Is it possible to do something like:

for (n in 100..1) {
    println(n)
}

And get results:

100
99
98
...

Range Solutions


Solution 1 - Range

Use downTo as in:

for (n in 100 downTo 1) {
//
}

Solution 2 - Range

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 - Range

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.

Solution 4 - Range

Reversed ranges are supported using the minus - unary operator as in -(1..100).

To invoke a method on that range, you will then need to surround it with parentheses as in

(-(1..100)).foreach { println(it) }

Solution 5 - Range

(100 downto 1).map{ println(it) }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjjnguyView Question on Stackoverflow
Solution 1 - RangeHadi HaririView Answer on Stackoverflow
Solution 2 - RangeletnerView Answer on Stackoverflow
Solution 3 - RangeEscape VelocityView Answer on Stackoverflow
Solution 4 - RangeFranck RasoloView Answer on Stackoverflow
Solution 5 - RangeCoolMindView Answer on Stackoverflow