Reputation: 67
I'm trying to do something like:
private val isOne = (x: Int) => x == 1
private val isTwo = (x: int) => x == 2
def main(x: Int): String = {
x match {
case isOne => "it's one!"
case isTwo => "it's two!"
case _ => ":( It's not one or two"
}
}
Unfortunately... doesn't look like my syntax is right or maybe that's just no possible in Scala... any suggestions?
Upvotes: 3
Views: 60
Reputation: 55569
This isn't going to work for two reasons. First,
case isOne => ...
is not what you think it is. isOne
within the match
is just a symbol that will eagerly match anything, and not a reference to the val isOne
. You can fix this by using backticks.
case `isOne` => ...
But this still won't do what you think it does. x
is an Int
, and isOne
is a Int => Boolean
, which means they will never match. You can sort of fix it like this:
def main(x: Int): String = {
x match {
case x if(isOne(x)) => "it's one!"
case x if(isTwo(x)) => "it's two!"
case _ => ":( It's not one or two"
}
}
But this isn't very useful, and case 1 => ....
does the job just fine.
Upvotes: 7