Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Ranges: Why isn't there a `downTo` variant to exclude last item like `until`?

Tags:

kotlin

Is there any declarative work around to exclude last item while decrementing looping, like using downTo?

like image 929
Gopal S Akshintala Avatar asked Sep 07 '19 14:09

Gopal S Akshintala


2 Answers

While the kotlin standard library does not include this utility, you can define your own extension functions for this purpose.

Looking at the stdlib, one definition of until is:

/**
 * Returns a range from this value up to but excluding the specified [to] value.
 * 
 * If the [to] value is less than or equal to `this` value, then the returned range is empty.
 */
public infix fun Int.until(to: Int): IntRange {
    if (to <= Int.MIN_VALUE) return IntRange.EMPTY
    return this .. (to - 1).toInt()
}

Therefore, we could define

infix fun Int.downUntil(to: Int): IntProgression {
    if (to >= Int.MAX_VALUE) return IntRange.EMPTY
    return this downTo (to + 1).toInt()
}

You may also want to define versions of this function to operate on other primitives.

like image 90
user10350526 Avatar answered Oct 26 '22 02:10

user10350526


for ( number in (0 until 10).reversed()) {
            println("$number using range until reversed")
        }

Even I was looking for downTo but didn't find but above implementation works

like image 38
Manoj Mohanty Avatar answered Oct 26 '22 01:10

Manoj Mohanty