Is there any declarative work around to exclude last item while decrementing looping, like using downTo
?
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.
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
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