Scala - 复杂的条件模式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6804225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala - complex conditional pattern matching
提问by Dominic Bou-Samra
I have a statement I want to express, that in C pseudo-code would look like this:
我有一个声明我想表达,在 C 伪代码中看起来像这样:
switch(foo):
case(1)
if(x > y) {
if (z == true)
doSomething()
}
else {
doSomethingElse()
}
return doSomethingElseEntirely()
case(2)
essentially more of the same
Is a nice way possible with the scala pattern matching syntax?
scala 模式匹配语法是一种很好的方法吗?
回答by Tomas Petricek
If you want to handle multiple conditions in a single matchstatement, you can also use guardsthat allow you to specify additional conditions for a case:
如果要在单个match语句中处理多个条件,还可以使用使您能够为案例指定附加条件的守卫:
foo match {
case 1 if x > y && z => doSomething()
case 1 if x > y => doSomethingElse()
case 1 => doSomethingElseEntirely()
case 2 => ...
}

