我想知道如何使用多种类型模式匹配。我有:
abstract class MyAbstract
case class MyFirst extends MyAbstract
case class MySecond extends MyAbstract
case class MyThird extends MyAbstract // shouldn't be matched and shouldn't call doSomething()
val x: MyAbstract = MyFirst
x match {
case a: MyFirst => doSomething()
case b: MySecond => doSomething()
case _ => doSomethingElse()
}
所以我想写一些类似的东西:
x match {
case a @ (MyFirst | MySecond) => doSomething()
case _ => doSomethingElse()
}
我在一些教程中看到了类似的构造,但是它给了我错误:
pattern type is incompatible with expected type;
[error] found : object MyFirst
[error] required: MyAbstract
那么有没有办法在on case子句中定义几种不同的类型?我认为这会使代码更漂亮。好像我将拥有5个一样,我将编写5次相同的代码(调用doSomething())。
提前致谢!
doSomething
情况下都有一个共同的超类,为什么不匹配case a : MyAbstract
那么...?