[英]Pattern Matching Against Anonymous
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? 不幸的是......看起来我的语法不对,或者在Scala中这是不可能的......任何建议?
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
. match
isOne
只是一个热切匹配任何东西的符号,而不是对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. x
是Int
, isOne
是Int => Boolean
,这意味着它们永远不会匹配。 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. 但这不是很有用, case 1 => ....
工作做得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.