我想用相同的条件来编写多个case语句,有没有一种不需要重复编写代码的方法?
"something" match {
case "a" if(variable) => println("a")
case "b" if(variable) => println("b")
// ...
}
我想用相同的条件来编写多个case语句,有没有一种不需要重复编写代码的方法?
"something" match {
case "a" if(variable) => println("a")
case "b" if(variable) => println("b")
// ...
}
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")
// ...
}
似乎OR(管道)运算符比守卫操作符具有更高的优先级,因此以下内容有效:
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__的答案是很好的。或者你可以先匹配“变量”:
variable match {
case true => s match {
case "a" | "b" | "c" => true
case _ => false
}
case _ => false
}