Scala模式匹配默认守卫

5

我想用相同的条件来编写多个case语句,有没有一种不需要重复编写代码的方法?

"something" match {
   case "a" if(variable) => println("a")
   case "b" if(variable) => println("b")
   // ...
 }

1
你能把代码分成分支吗?那么把“如果变量”的部分拿出来,在里面进行匹配,对于其他的分支也是同样的处理吗? - aishwarya
3个回答

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")
  // ...
}

7

似乎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 ))

4

0__的答案是很好的。或者你可以先匹配“变量”:

variable match {
  case true => s match {
    case "a" | "b" | "c" => true
    case _ => false
  }
  case _ => false
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接