Reputation: 3185
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
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
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
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