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 ...
To create a range for your class, call the rangeTo() function on the range start value and provide the end value as an argument. rangeTo() is often called in its operator form .. .
Kotlin range is defined as an interval from start value to the end value. Range expressions are created with operator (. .) which is complemented by in and !in. The value which is equal or greater than start value and smaller or equal to end value comes inside the definedrange.
operator. It is the simplest way to work with range. It will create a range from the start to end including both the values of start and end. It is the operator form of rangeTo() function.
Use downTo as in:
for (n in 100 downTo 1) { // }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With