Scala - 复杂条件模式匹配

Dom*_*mra 16 scala pattern-matching

我有一个我要表达的声明,在C伪代码中看起来像这样:

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

    case(2)
        essentially more of the same
Run Code Online (Sandbox Code Playgroud)

使用scala模式匹配语法是一种很好的方法吗?

Tom*_*cek 44

如果要处理多个条件,在一个match声明中,您还可以使用守卫,允许您指定的情况下,附加条件:

foo match {    
  case 1 if x > y && z => doSomething()
  case 1 if x > y => doSomethingElse()
  case 1 => doSomethingElseEntirely()
  case 2 => ... 
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上与OP写的不一致.控制流程不同; 在`x> y && z`上,OP执行`doSomething()`,`return doSomethingElseEntirely()`,而你的执行只返回`doSomething()`. (5认同)
  • @Paul我同意,但要求这种解决方案是OP!:) (2认同)