Kotlin Ranges:为什么没有一个 `downTo` 变体来排除像 `until` 这样的最后一项?

Gop*_*ala 5 kotlin

在递减循环时是否有任何声明性工作来排除最后一项,例如使用downTo

小智 3

虽然 kotlin 标准库不包含此实用程序,但您可以为此目的定义自己的扩展函数。

查看 stdlib,until 的一个定义是:

/**
 * 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()
}
Run Code Online (Sandbox Code Playgroud)

因此,我们可以定义

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

您可能还想定义此函数的版本以对其他原语进行操作。