Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: short form of pattern matching that returns Boolean

I found myself writing something like this quite often:

a match {        case `b` => // do stuff   case _ => // do nothing } 

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff 

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

like image 990
Vilius Normantas Avatar asked Dec 14 '10 08:12

Vilius Normantas


People also ask

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 matchers in Scala?

It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala's root class to make its availability to the all objects.

What is case class and pattern matching in Scala?

It is defined in Scala's root class Any and therefore is available for all objects. The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.

What is pattern matching syntax?

Patterns are written in JME syntax, but there are extra operators available to specify what does or doesn't match. The pattern-matching algorithm uses a variety of techniques to match different kinds of expression.


1 Answers

This is exactly why I wrote these functions, which are apparently impressively obscure since nobody has mentioned them.

scala> import PartialFunction._ import PartialFunction._  scala> cond("abc") { case "def" => true } res0: Boolean = false  scala> condOpt("abc") { case x if x.length == 3 => x + x } res1: Option[java.lang.String] = Some(abcabc)  scala> condOpt("abc") { case x if x.length == 4 => x + x } res2: Option[java.lang.String] = None 
like image 116
psp Avatar answered Sep 21 '22 12:09

psp