Lukasz
Lukasz

Reputation: 3185

Scala pattern match default guards

I want to do many case statements with same guard in front of each. Can I do it in way that doesn't require code duplication ?

"something" match {
   case "a" if(variable) => println("a")
   case "b" if(variable) => println("b")
   // ...
 }

Upvotes: 5

Views: 6038

Answers (3)

Eun Woo Song
Eun Woo Song

Reputation: 740

0__'s answer is a good one. Alternatively You can match against the "variable" first:

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

Upvotes: 4

0__
0__

Reputation: 67280

It seems that the OR (pipe) operator has higher precedence than the guard, 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 ))

Upvotes: 6

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297185

You could 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")
  // ...
}

Upvotes: 7

Related Questions