如何在 Scala 中模式匹配多个值?
假设我想使用相同的代码处理来自远程服务的多个返回值。我不知道如何在 Scala 中表达这一点:
code match {
case "1" => // Whatever
case "2" => // Same whatever
case "3" => // Ah, something different
}
我知道我可以使用 Extract Method 并调用它,但调用中仍然存在重复。如果我使用 Ruby,我会这样写:
case code
when "1", "2"
# Whatever
when "3"
# Ah, something different
end
请注意,我简化了示例,因此我不想对正则表达式或类似表达式进行模式匹配。匹配值实际上是复数值。
Let's say I want to handle multiple return values from a remote service using the same code. I don't know how to express this in Scala:
code match {
case "1" => // Whatever
case "2" => // Same whatever
case "3" => // Ah, something different
}
I know I can use Extract Method and call that, but there's still repetition in the call. If I were using Ruby, I'd write it like this:
case code
when "1", "2"
# Whatever
when "3"
# Ah, something different
end
Note that I simplified the example, thus I don't want to pattern match on regular expressions or some such. The match values are actually complex values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作:
请注意,您无法将模式的一部分绑定到名称 - 目前您无法执行此操作:
You can do:
Note that you cannot bind parts of the pattern to names - you can't do this currently:
另一个答案正确地说,目前无法在提取时对多个替代方案进行模式匹配同时值。
我想与您分享一种接近此目的的编码模式。
Scala 允许您在不提取值的情况下对替代方案进行模式匹配,例如
case Dog(_, _) |猫(_,_)=> ...
是合法的。使用它,您可以简单地在 case 块中自己提取值。这是一个有点人为的示例:
假设
???
实际上代表做对狗和猫来说相同的事情。如果没有这种编码模式,您将需要两种情况,一种用于狗,一种用于猫,迫使您重复代码或至少将代码外包到函数中。一般来说,如果您有共享字段的同级案例类,并且这些字段的行为仅对于某些算法相同,那么上面的编码模式是合适的。在这些情况下,您无法将这些字段提取到公共超类中。尽管如此,您仍然希望在算法中以统一的方式对这些字段进行模式匹配,以平等对待它们。您可以按照上图所示执行此操作。
The other answer correctly says that currently there is no way to pattern-match multiple alternatives while extracting values at the same time.
I'd like to share a coding pattern with you that comes close to doing this.
Scala allows you to pattern-match alternatives without extracting values, e.g.
case Dog(_, _) | Cat(_, _) => ...
is legal. Using this, you can simply extract the values yourself within the case block.Here's a somewhat contrived example:
Assume that
???
actually stands for doing something that is equal for dogs and cats. Without this coding pattern, you would need to have two cases, one for dogs and one for cats, forcing you to duplicate code or at least to outsorce code into a function.Generally, the coding pattern above is suitable if you have sibling case classes that share fields that behave identically only for some algorithms. In those cases, you cannot extract those fields to a common superclass. Still, you would like to pattern-match in a uniform way on those fields in the algorithms that treat them equally. This you can do as shown above.