Scala: short form of pattern matching that returns Boolean

Vilius Normantas picture Vilius Normantas · Dec 14, 2010 · Viewed 15k times · Source

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

Answer

psp picture psp · Dec 14, 2010

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