Here is how I would implement it:
implicit class RangeHasShift(val r: Range) extends AnyVal {
def shift(n: Int): Range = {
val start1 = r.start + n
val end1 = r.end + n
// overflow check
if ((n > 0 && (start1 < r.start || end1 < r.end)) ||
(n < 0 && (start1 > r.start || end1 > r.end)))
throw new IllegalArgumentException(s"$r.shift($n) causes number overflow")
if (r.isInclusive)
new Range.Inclusive(start1, end1, r.step)
else
new Range (start1, end1, r.step)
}
}
def check(r: Range) = assert(r == r.shift(123).shift(-123))
check(1 to 10)
check(1 to -1)
check(1 to -1 by -1)
check(1 to 10 by 3)
check(1 until 10)
check(1 until -1)
check(1 until -1 by -1)
check(1 until 10 by 3)
I wonder if this exists somewhere in the API?