Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a range be matched in Scala?

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?

like image 631
Justin Poliey Avatar asked Aug 28 '09 10:08

Justin Poliey


People also ask

How do you use a range in Scala?

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.

Does Scala have pattern matching?

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.

How does match work in Scala?

“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.

What is the default option in a match case in Scala?

getList("instance").


2 Answers

Guard using Range:

val m = t match {   case x if 0 until 10 contains x => true   case _ => false } 
like image 159
Alexander Azarov Avatar answered Oct 20 '22 13:10

Alexander Azarov


You can use guards:

val m = t match {     case x if (0 <= x && x < 10) => true     case _ => false } 
like image 28
Alexey Romanov Avatar answered Oct 20 '22 13:10

Alexey Romanov