Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin can I create a range that counts backwards?

Tags:

range

kotlin

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 ... 
like image 877
jjnguy Avatar asked Mar 05 '12 06:03

jjnguy


People also ask

How do you set range on Kotlin?

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

What is range expressions in Kotlin?

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.

What is operator in Kotlin What's the advantage of using ranges?

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.


2 Answers

Use downTo as in:

for (n in 100 downTo 1) { // } 
like image 192
Hadi Hariri Avatar answered Sep 22 '22 02:09

Hadi Hariri


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 } 
like image 35
letner Avatar answered Sep 24 '22 02:09

letner