Scala多types模式匹配

我想知道如何使用多种types的模式匹配。 我有:

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 

那么有没有办法在case子句中定义几个不同的types呢? 我认为这会使代码更漂亮。 就好像我将有5个,我会写相同的代码5次(调用doSomething())。

提前致谢!

您缺less您的案例类的括号。 不包含参数列表的案例类别已被弃用。

尝试这个:

 abstract class MyAbstract case class MyFirst() extends MyAbstract case class MySecond() extends MyAbstract val x: MyAbstract = MyFirst() x match { case aOrB @ (MyFirst() | MySecond()) => doSomething(aOrB) case _ => doSomethingElse() } 

如果你的case类有太多的参数,不想写长的Foo(_,_,..)模式,那么也许:

 x match { case aOrB @ (_:MyFirst | _:MySecond) => doSomething(aOrB) case _ => doSomethingElse() } 

要不就:

 x match { case _:MyFirst | _:MySecond => doSomething(x) // just use x instead of aOrB case _ => doSomethingElse(x) } 

但也许你只是想单身的案件对象?

 abstract class MyAbstract case object MyFirst extends MyAbstract case object MySecond extends MyAbstract val x: MyAbstract = MyFirst x match { case aOrB @ (MyFirst | MySecond) => doSomething() case _ => doSomethingElse() }