Scala default pattern matching

I want to make many arguments with the same guard in front of everyone. Can I make it so that code duplication is not required?

"something" match {
   case "a" if(variable) => println("a")
   case "b" if(variable) => println("b")
   // ...
 }
+5
source share
3 answers

You can create an extractor:

class If {
  def unapply(s: Any) = if (variable) Some(s) else None
}
object If extends If
"something" match {
  case If("a") => println("a")
  case If("b") => println("b")
  // ...
}
+8
source

The OR (pipe) operator seems to have a higher priority than the defender, so the following works:

def test(s: String, v: Boolean) = s match {
   case "a" | "b" if v => true
   case _ => false
}

assert(!test("a", false))
assert( test("a", true ))
assert(!test("b", false))
assert( test("b", true ))
+7
source

0__ answer is good. Alternatively, you can first map the "variable":

variable match {
  case true => s match {
    case "a" | "b" | "c" => true
    case _ => false
  }
  case _ => false
}
+4
source

All Articles