我想在每个语句前面用相同的守卫做许多 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")
// ...
}
关于Scala 模式匹配默认守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007234/