具有多个匹配项的模式匹配
考虑以下 Scala 代码。
val a = "both"
a match {
case "both" | "foo" => println ("foo") // case 1
case "both" | "bar" => println ("bar") // case 2
}
我希望 match
能够工作,以便如果 a == "both"
,Scala 将执行这两种情况。这是可能的还是有其他选择来实现我想要的?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
标准模式匹配将始终只匹配一种情况。通过使用模式可以被视为部分函数这一事实,您可以接近您想要的内容(请参阅 语言规范,第 8.5 节,模式匹配匿名函数)并通过定义您自己的匹配运算符,虽然:
语法稍微偏离通常,但对我来说这样一个构造仍然是Scala 力量的见证。
你的例子现在写成:(
编辑huynhjl指出他给出了一个可怕的相似答案到这个问题。)
Standard pattern-matching will always match on only exactly one case. You can get close to what you want by using the fact that patterns can be treated as partial functions (see the Language Specification, Section 8.5, Pattern Matching Anonymous Functions) and by defining your own matching operator, though:
The syntax is slightly off the usual, but to me such a construction is still a witness to the power of Scala.
Your example is now written as:
(Edit huynhjl pointed out that he gave a frighteningly similar answer to this question.)
冒着成为明显队长的风险,在这种情况下,最简单的方法就是忘记模式匹配并使用
if
。如果
a ==
的重复让您担心,您可以使用
Set
上的apply
方法与相同的事实来 编写>包含
,并且有点短。At risk of being Captain Obvious, in a case like this it would be simplest just to forget pattern matching and use
if
.If the repetition of
a ==
worries you, you could instead writeusing the fact that the
apply
method onSet
does the same ascontains
, and is a bit shorter.match
执行一种且仅一种情况,因此您不能在匹配中将其作为or
执行。但是,您可以使用列表和map
/foreach
:并且您不会重复任何重要代码(在本例中为
printlns)。
match
executes one, and only one, of the cases, so you can't do this as anor
in the match. You can, however, use a list andmap
/foreach
:And you're not duplicating any of the important code (in this case the
println
s).只需匹配两次:
Just match twice:
一种可能的方法是:
One possible way could be: