Scala多类型模式匹配

bsxbgnwa  于 2022-12-23  发布在  Scala
关注(0)|答案(1)|浏览(171)

我想知道如何使用多类型模式匹配。我有:

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())。

rryofs0p

rryofs0p1#

事例类缺少括号。不推荐使用不带参数列表的事例类。
试试这个:

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)
}

但也许您只是想要单例case对象?

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()
}

相关问题