Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pattern match on a range in Scala?

In Ruby I can write this:

case n when 0...5  then "less than five" when 5...10 then "less than ten" else "a lot" end 

How do I do this in Scala?

Edit: preferably I'd like to do it more elegantly than using if.

like image 244
Theo Avatar asked Jul 01 '10 19:07

Theo


People also ask

How do you match a pattern in Scala?

A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.

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.

What is the use of Scala pattern matching?

Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .


1 Answers

Inside pattern match it can be expressed with guards:

n match {   case it if 0 until 5 contains it  => "less than five"   case it if 5 until 10 contains it => "less than ten"   case _ => "a lot" } 
like image 82
Yardena Avatar answered Oct 14 '22 21:10

Yardena