如何在 Scala 中模式匹配多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7209728/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:23:58  来源:igfitidea点击:

How to pattern match multiple values in Scala?

scalapattern-matching

提问by Fran?ois Beausoleil

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:

假设我想使用相同的代码处理来自远程服务的多个返回值。我不知道如何在 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:

我知道我可以使用 Extract Method 并调用它,但是调用中仍然存在重复。如果我使用 Ruby,我会这样写:

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.

请注意,我简化了示例,因此我不想对正则表达式等进行模式匹配。匹配值实际上是复杂的值。

回答by axel22

You can do:

你可以做:

code match {
  case "1" | "2" => // whatever
  case "3" =>
}

Note that you cannot bind parts of the pattern to names - you can't do this currently:

请注意,您不能将模式的一部分绑定到名称 - 目前您不能这样做:

code match {
  case Left(x) | Right(x) =>
  case null =>
}