Scala模式匹配默认警卫

Luk*_*asz 5 scala pattern-matching

我想在每个案件前面做同样的警卫.我可以这样做,不需要代码重复吗?

"something" match {
   case "a" if(variable) => println("a")
   case "b" if(variable) => println("b")
   // ...
 }
Run Code Online (Sandbox Code Playgroud)

Dan*_*ral 8

你可以创建一个提取器:

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")
  // ...
}
Run Code Online (Sandbox Code Playgroud)


0__*_*0__ 7

似乎OR(管道)运算符的优先级高于guard,因此以下工作原理:

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 ))
Run Code Online (Sandbox Code Playgroud)