2011-07-24 29 views
14

我有我想要表达的一份声明中,在C伪代码是这样的:斯卡拉 - 复杂的条件模式匹配

switch(foo): 
    case(1) 
     if(x > y) { 
      if (z == true) 
       doSomething() 
      } 
      else { 
       doSomethingElse() 
      } 
     return doSomethingElseEntirely() 

    case(2) 
     essentially more of the same 

是一个很好的方式可能与Scala的模式匹配语法?

回答

37

如果要处理多个条件一次match语句,你还可以使用卫士,让你的情况下指定的附加条件:

foo match {  
    case 1 if x > y && z => doSomething() 
    case 1 if x > y => doSomethingElse() 
    case 1 => doSomethingElseEntirely() 
    case 2 => ... 
} 
+0

啊,没想到有几个案例1的。这样可行。 –

+5

这实际上并不符合OP所写的内容。控制流程不同;在'x> y && z'上,OP执行'doSomething()','return doSomethingElseEntirely()',而你的函数只返回'doSomething()'。 –

+0

@Rex - 好的,谢谢。我不太明白,因为OP的代码缺少一些开启和关闭的花括号。无论如何,应该很容易相应地修复身体。 –