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 :)
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.
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.
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.
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.
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
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