Moritz Groß
Moritz Groß

Reputation: 1490

Range of two arbitrary numbers

In Kotlin, one can create a range of two numbers by writing a..b, but a < b is necessary for this to not be empty.

Is there a short way for creating the range "between" two arbitrary numbers? The logic for this would be: min(a,b)..max(a,b)

Upvotes: 4

Views: 1014

Answers (1)

gidds
gidds

Reputation: 18547

There's no short way built into the standard library, I'm afraid.  But you can easily add your own.  Your question gives one way:

fun rangeBetween(a: Int, b: Int) = min(a, b) .. max(a, b)

And here's another:

fun rangeBetween(a: Int, b: Int) = if (a > b) a downTo b else a .. b

(They both behave the same for in checks, but differ in the iteration order: the first one always counts up from the lower to the higher, while the latter will count up or down from the first number to the second.)

Unfortunately those can't be made generic, as both the min()/max() methods and the type of range are different for Ints, Longs, Bytes, Shorts, etc.  But you could add overloads for other types if needed.

(I don't know why Kotlin is so fussy about distinguishing ascending and descending ranges.  You'd think that this was a fairly common case, and that it would be a simplification to allow ranges to count up or down as needed.)

Upvotes: 2

Related Questions