Scala - pattern matching with conditional statements?
Is it possible to do something like:
def foo(x: Int): Boolean = {
c开发者_StackOverflow中文版ase x > 1 => true
case x < 1 => false
}
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...
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)
Since the case of x == 1
is missing in your example, I assume that it is handled just the same as 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
精彩评论