在 Kotlin,我可以创建一个向后计数的范围吗?

我查看了 山脉的文件,没有看到任何关于向后范围的内容。

有没有可能做这样的事情:

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

然后得到结果:

100
99
98
...
40605 次浏览

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

Use downTo as in:

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

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.

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

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
}