【发布时间】:2013-03-17 08:31:15
【问题描述】:
我想知道如何使用多种类型的模式匹配。我有:
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())。
提前致谢!
【问题讨论】:
-
我认为这是一个 XY 问题;对于所有
doSomething案例,您都有一个共同的超类,为什么不匹配case a : MyAbstract然后...? -
抱歉,忘了说,我还有其他类,它们扩展了 MyAbstract 类,不应该调用 doSomething。
-
哦,好的,只是想澄清一下 :) 你现在有一个正确的答案来解决你的问题。
标签: scala types pattern-matching