Search code examples
kotlinrangeequals

Why are 2 kotlin descending IntRanges equal?


It appears kotlin considers different valued descending IntRanges as equal. Is this because they are all considered invalid?

@Test
fun abc() {
    var a:IntRange = (1..2)
    var b:IntRange = (1..3)
    println(a==b) // prints false
    var c:IntRange = (10..1)
    var d:IntRange = (9..1)
    println(c==d) // prints true
    println(c) // prints 10..1
    println(d) // prints 9..1
}

Solution

  • The documentation for the IntRange.isEmpty says:

    The range is empty if its start value is greater than the end value.

    Therefore, both 10..1 and 9..1 will be empty ranges, and empty ranges are considered equal in the current implementation of equals.

    If you want a sequence that goes from 10 down to 1, you might be looking for the downTo infix function instead. Note that this gives you a more general IntProgression, not an IntRange.

    val from10To1 = 10 downTo 1