Is there a support for number range check

Hi Team,

I was wondering if we have support for number range check with syntactic sugar as an alternative to below code.

val foo: Option[Long]
foo.exists(ele => ele <= min && ele <= max )

I was looking for something like

foo.exists(inInclusiveRange(min,max))

Wanted to check if we already have any similar functionality in recent versions ?

Yeah, you can use Range.contains: Range

Like this:

foo.exists((min to max).contains)

See the code running here: Scastie - An interactive playground for Scala.

The problem with using range is that it’s step valued, and hence for large interval throws exception.

val range: NumericRange.Inclusive[Long] = 0L to 123456789011L
val foo: Option[Long] = Some(123456789010L)
val bar = foo.exists(range.contains[Long])

java.lang.IllegalArgumentException: More than Int.MaxValue elements.

I see there’s a check in NumericRange which prohibits large intervals.

def check(t: T): T =
        if (num.gt(t, limit)) throw new IllegalArgumentException("More than Int.MaxValue elements.")
        else t

Then you would need to make your own Range like class or helper method.
Which is probably way more work than the if, unless you repeat this a lot with different bounds.

Perhaps you misspelt cats.collections.Range as scala.collections.immutable.Range - see here and here. :smile:

I’ve not tried this myself, but will leave as an exercise to the proverbial reader.

3 Likes

Yeah this one works !!
I wasn’t using cats collection in my code so far.

Thanks for the help.

1 Like