kotlin

Kotlin "for loop" downTo exclusive


How to write this Java code in Kotlin?

//Java
for (int i = 10; i > 0; i--);

As you can see, "i" can not be zero.

I know this one can be done with "downTo" like this:

for (i in 10 downTo 0)

But "downTo" is inclusive of zero. I want it to be exclusive of zero. My question is, is there a way to do that in Kotlin? (only within the "for loop", without changing zero or ten, and without any additional "if"s or anything)


Solution

  • There is no built-in method that creates a decreasing progression with an exclusive end value. A downUntil function that creates such a progression has been proposed in KT-24658, which is currently "to be discussed". If you have practical use cases where downUntil would be convenient, I encourage you to join in the discussion there.

    It is easy to write such a function yourself:

    infix fun Int.downUntil(until: Int) =
        IntProgression.fromClosedRange(this, until + 1, -1)
    
    // ...
    
    for (i in 10 downUntil 0) { ... }
    

    However, unlike the built-in downTo, the compiler will not optimise this to a C-style for loop in bytecode. It will create a IntProgression object and use its iterator() to run the loop.

    I recommend using 10 downTo 1 for the time being.