Is it possible to match a range of values in Scala?
For example:
val t = 5 val m = t match { 0 until 10 => true _ => false }
m
would be true
if t
was between 0 and 10, but false otherwise. This little bit doesn't work of course, but is there any way to achieve something like it?
For example, "1, 2, 3," is a range, as is "5, 8, 11, 14." To create a range in Scala, use the predefined methods to and by. Ranges are represented in constant space, because they can be defined by just three numbers: their start, their end, and the stepping value.
Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
“match” is always defined in Scala's root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched.
getList("instance").
Guard using Range
:
val m = t match { case x if 0 until 10 contains x => true case _ => false }
You can use guards:
val m = t match { case x if (0 <= x && x < 10) => true case _ => false }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With