In Kotlin can I create a range that counts backwar

2019-02-21 09:52发布

问题:

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

回答1:

Use downTo as in:

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


回答2:

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



回答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.



回答4:

If you look at the exact page you linked to, there's a suggestion for a reversed function that would let you do for (n in (1..100).reversed()) but it doesn't appear to be implemented yet. The .. operator always counts up.



回答5:

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
}


回答6:

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


标签: range kotlin