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


85

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

请注意,我简化了示例,因此我不想在正则表达式或某些此类表达式上进行模式匹配。匹配值实际上是复数值。


Answers:


149

你可以做:

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

请注意,您无法将模式的某些部分绑定到名称-您目前无法执行以下操作:

code match {
  case Left(x) | Right(x) =>
  case null =>
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.