In Kotlin can I create a range that counts backwards?

kotlin range
range step kotlin
kotlin closedrange
kotlin for loop arraylist
what is operator in kotlin what's the advantage of using ranges
kotlin for each
for loop count kotlin
kotlin infinite loop

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

And get results:


Use downTo as in:

for (n in 100 downTo 1) {

In Kotlin can I create a range that counts backwards?, Use downTo as in: for (n in 100 downTo 1) { // }. In Kotlin, these progressions are defined by special types: IntProgression, LongProgression, and CharProgression. Progressions have three essential properties: the first element, the last element, and a non-zero step . The first element is first, subsequent elements are the previous element plus a step.

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

How to use Kotlin Range Expressions, In Kotlin, we can create ranges using the rangeTo() and downTo() Also, if we want to define a backward range we can use the downTo operator: ? we can apply to our range, like min, max, sum, average, count, distinct: ? In Kotlin, we can create ranges using the rangeTo() and downTo() functions or the .. operator. We can use ranges for any comparable type. By default, they're inclusive, which means that the 1..4 expression corresponds to the values 1,2,3 and 4.

As pointed by others, the correct answer is

for (n in 100 downTo 1) {

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.

Kotlin Ranges, The range in Kotlin consists of a start, a stop, and the step. operator we can create range for integers as well as characters. Below we create range in reverse order for integer and characters both. Python - Initialize empty array of given length · Count of subarrays having exactly K distinct elements · Map of Vectors in  A Kotlin range is created with the .. operator or with the rangeTo() and downTo() functions. Kotlin ranges are inclusive by default; that is, 1..3 creates a range of 1, 2, 3 values. The distance between two values is defined by the step; the default step is 1. Kotlin range creation. The following example shows how to create simple ranges in Kotlin.

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)


// 0 to 100
for (i in 0 toward 100) {
    // Do things

// 100 downTo 0
for (i in 100 toward 0) {
    // Do things

Android Studio 3.6 Development Essentials, The following for loop counts backwards from 100 until the number 90 is reached: When executed, the above loop will generate the following output: 100. way with the exception that counting starts from the bottom of the collection range  그러나 Kotlin 팀은 왜 100 downTo 1 대 100..1 선택 100..1 습니까? 리터럴 대신 변수를 사용하려고하면 구문 100..1 이 좋지 않을 것이라고 생각합니다. 입력 한 경우 . for (n in b..a) 어떤 루프를 사용하고 싶었는지 명확하지 않습니다.

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.

Learn Kotlin, You can create a range in Kotlin via .. operator. { for(iin 1..5) { print(i) } } Output: 12345 Using downTo function we can go reverse in a range. { for(iin 5 downTo 1) { print(i) } } Output: 54321 Using step function we can increase the step count. If you need to count downwards, use the inclusive downTo: for (x in 10 downTo 0 step 2) println(x) // Prints 10, 8, 6, 4, 2, 0 Any of the expressions to the right of in in the loops above can also be used outside of loops in order to generate ranges (one type of iterables - this is similar to xrange() in Python 2 and range() in Python 3), which

Kotlin / Android Studio 3.0 Development Essentials, The following for loop counts backwards from 100 until the number 90 is When executed, the above loop will generate the following output: 100.. 99.. 98. that counting starts from the bottom of the collection range and works up until (but not​  In Kotlin you currently need to use the platform specific ones (there isn't a Kotlin built in one). For the JVM it's java.util.Random . You'll need to create an instance of it and then call random.nextInt(n) .

Kotlin Ranges tutorial - working with ranges in Kotlin, In this line, we reverse the range with reversed() and loop over the range with forEach() . 1 2 3 4 5 5 4 3 2 1. This is the output. Kotlin range iterator. We can use the  kotlin-stdlib / kotlin.ranges / IntRange. fun < T > Iterable < T >. count Returns a random element from this range using the specified source of randomness.

Kotlin sets tutorial - working with sets in Kotlin, The setOf() method creates a new read-only set in Kotlin. KotlinSetOf.kt The count() can take a predicate function as a parameter. In our case it The until keyword creates a range of the set indexes. words. val revNums = nums.​reversed(). Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more Kotlin VerifyError: Uninitialized object exists on backward branch 90

  • Why it's not "for (n in 100..1)"? Couldn't it be an agreement that if the first number is bigger then a range counts backwards?
  • Is there something that excludes the lower limit ? e.g. if I want from 100 till 2. and want to exclude 1.
  • @x2bool, though it is useful, there are situations, where it is not. For instance, you want to loop from 0 to count - 1, but don't want to check limits (like in Java). If count becomes 0, you will have 0 downto -1 which will break an algorythm.
  • @MobileAppDeveloper, if limits are integer, you can add 1 to lower limit.
  • Is there any possibility of making the rangeTo() function a bit smarter and handling that automatically? Having a negative range to me means counting from -1 to -100.
  • I suggest you take a look at the following issues related to ranges in Kotlin and submit a new issue explaining in detail your suggestion: KT-861, KT-1045, KT-1076
  • This doesn't pass static analysis in kotlin 1.3
  • So there is no native Kotlin equivalent to this?
  • I haven't found one. You can get the same result, for example using step function for some Progression, but still need to calculate the step by yourself. I suppose, Kotlin architects want to create a perfectly readable language. That means code execution have to be exactly the same as written, and universal infix function like my "toward" doesn't completely fit to that idea.
  • I saw that comment and hoped it was out of date.
  • @jjnguy hmm... perhaps it is. Commit 86a33f8 (Jan 18 2012) adds tests for for (n in 100 downto 1) and for (n in -(1..100)) both having the same meaning. Do they work for you?
  • -(1..100) no longer works. The correct syntax is for (n in 100 downTo 1)