scala:将匹配语句转换为模式匹配匿名函数 - 带有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29332799/
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: convert match statement to pattern matching anonymous function - with values
提问by Daniel Hanke
like similar question: Convert match statement to partial function when foreach is used. Now similarly, IntelliJ asks me to improve my code. The difference is, that I use values for the matching:
像类似的问题:Convert match statement to partial function when foreach is used。现在类似地,IntelliJ 要求我改进我的代码。不同之处在于,我使用值进行匹配:
val matchMe = "Foo"
keys.foreach(key =>
key match {
case `matchMe` => somethingSpecial()
case _ => somethingNormal(key, calcWith(key))
})
Refactoring this to a anonymous pattern-matching function would look something like:
将其重构为匿名模式匹配函数将如下所示:
keys.foreach {
case `matchMe` => somethingSpecial(_)
case _ => somethingNormal(_, calcWith(_)) //this doesn't work
}
Note that in the second case, I cannot use _since I need it twice. Is there some way to use an anonymous pattern-matching function here?
请注意,在第二种情况下,我无法使用,_因为我需要它两次。有什么方法可以在这里使用匿名模式匹配功能吗?
回答by Marth
You can't use the wildcard _here, its purpose is to indicate you don't care about the value you're matching against.
您不能在_此处使用通配符,它的目的是表明您不关心要匹配的值。
You can use a named parameter :
您可以使用命名参数:
keys.foreach {
case `matchMe` => somethingSpecial(matchMe)
case nonSpecialKey => somethingNormal(nonSpecialKey, calcWith(nonSpecialKey))
}
Without any restrictions placed on it, it will match any value. Do note that the order of cases is important, as case x => ...match anything and will essentially shortcut other casestatements.
没有任何限制,它将匹配任何值。请注意cases的顺序很重要,因为case x => ...匹配任何内容并且本质上会缩短其他case语句。
As an aside, I don't think your somethingSpecial(_)does what you want/expect it to. It's only a short version of x => somethingSpecial(x), not somethingSpecial(matchMe).
顺便说一句,我认为您somethingSpecial(_)不会做您想要/期望的事情。它只是 的一个简短版本x => somethingSpecial(x),而不是somethingSpecial(matchMe)。

