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)
}
???
}
假设??? 实际上代表对狗和猫做同样的事情。如果没有这种编码模式,您将需要两种情况,一种用于狗,一种用于猫,这会迫使您重复代码或至少将代码外包到函数中。
通常,如果您有兄弟案例类共享行为相同的字段仅对某些算法,则上述编码模式适用。在这些情况下,您无法将这些字段提取到公共超类中。尽管如此,您仍希望以统一的方式对算法中的那些字段进行模式匹配,以平等对待它们。您可以如上所示执行此操作。