Scala - 与条件语句的模式匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6740864/
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 - pattern matching with conditional statements?
提问by Dominic Bou-Samra
Is it possible to do something like:
是否可以执行以下操作:
def foo(x: Int): Boolean = {
case x > 1 => true
case x < 1 => false
}
回答by dhg
def foo(x: Int): Boolean =
x match {
case _ if x > 1 => true
case _ if x < 1 => false
}
Note that you don't have a case for x == 1 though...
请注意,尽管您没有 x == 1 的情况...
回答by michael.kebe
I would write something like this:
我会写这样的东西:
def foo(x: Int) = if (x > 1) true
else if (x < 1) false
else throw new IllegalArgumentException("Got " + x)
回答by Madoc
Since the case of x == 1is missing in your example, I assume that it is handled just the same as x < 1.
由于x == 1您的示例中缺少的情况,我假设它的处理方式与x < 1.
You can do it like this:
你可以这样做:
def foo(x:Int):Boolean = (x - 1).signum match {
case 1 => true
case _ => false
}
But then, this can of course be simplified a lot:
但是,这当然可以简化很多:
def foo(x:Int) = (x - 1).signum == 1

