Scala 模式匹配默认防护



我想做很多案例陈述,每个案例前面都有相同的警卫。我可以以不需要代码重复的方式做到这一点吗?

"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
}

最新更新