Comparing templates with anonymous
I am 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 one!"
case isTwo => "it two!"
case _ => ":( It not one or two"
}
}
Unfortunately ... doesn't seem like my syntax is correct or maybe it's just not possible in Scala ... any suggestions?
source to share
This will not work for two reasons. Firstly,
case isOne => ...
is not what you think. isOne
inside match
is just a character that will readily match anything, not a reference to val isOne
. You can fix this by using backlinks.
case `isOne` => ...
But it still won't do what you think it does. x
- this Int
, a isOne
- Int => Boolean
, which means they will never match. You can fix it like this:
def main(x: Int): String = {
x match {
case x if(isOne(x)) => "it one!"
case x if(isTwo(x)) => "it two!"
case _ => ":( It not one or two"
}
}
But this is not very useful and case 1 => ....
works great.
source to share