【问题标题】:How to pattern match multiple values in Scala?如何在Scala中模式匹配多个值?
【发布时间】:2011-11-04 19:13:41
【问题描述】:

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

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

【问题讨论】:

标签: scala pattern-matching


【解决方案1】:

你可以这样做:

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

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

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

【讨论】:

    【解决方案2】:

    The other answer 正确地表示,目前没有办法在同时提取值的同时对多个备选方案进行模式匹配。 我想与您分享一个接近于这样做的编码模式。

    Scala 允许您在不提取值的情况下对备选方案进行模式匹配,例如case Dog(_, _) | Cat(_, _) => ... 是合法的。使用它,您可以简单地自己在 case 块中提取值。

    这是一个有些人为的例子:

    abstract class Animal
    case class Dog(age: Int, barkLevel: Int) extends Animal
    case class Cat(apparentAge: Int, cutenessLevel: Int) extends Animal
    
    val pet: Animal = Dog(42, 100)
    
    // Assume foo needs to treat the age of dogs and the apparent age
    // of cats the same way.
    // Same holds for bark and cuteness level.
    def foo(pet: Animal): Unit = pet match {
      case animal@(Dog(_, _) | Cat(_, _)) =>
    
        // @unchecked suppresses the Scala warning about possibly
        // non-exhaustiveness even though this match is exhaustive
        val (agelike, level) = (animal: @unchecked) match {
          case Dog(age, barkLevel) => (age, barkLevel)
          case Cat(apparentAge, cutenessLevel) => (apparentAge, cutenessLevel)
        }
    
        ???
    }
    

    假设??? 实际上代表对狗和猫做同样的事情。如果没有这种编码模式,您将需要两种情况,一种用于狗,一种用于猫,这会迫使您重复代码或至少将代码外包到函数中。

    通常,如果您有兄弟案例类共享行为相同的字段仅对某些算法,则上述编码模式适用。在这些情况下,您无法将这些字段提取到公共超类中。尽管如此,您仍希望以统一的方式对算法中的那些字段进行模式匹配,以平等对待它们。您可以如上所示执行此操作。

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 2013-03-17
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多