2012-08-17 55 views
5

我想在每个前面做同样的警卫许多案例陈述。我可以这样做,不需要代码重复吗?斯卡拉模式匹配默认警卫

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

您可以将代码分解为分支吗?所以请拔出“如果变量”并在里面进行匹配,对于其他任何分支您也是如此? – aishwarya 2012-08-17 13:59:57

回答

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 
}