2012-08-17 70 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 
}