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")
// ...
}
getList("instance").
A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.
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.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
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")
// ...
}
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 ))
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
}
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