Scala 多类型模式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15655817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala multiple type pattern matching
提问by psisoyev
I'm wondering how can I use multiple type pattern matching. I have:
我想知道如何使用多类型模式匹配。我有:
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()
}
So I'd like to write something like:
所以我想写一些类似的东西:
x match {
case a @ (MyFirst | MySecond) => doSomething()
case _ => doSomethingElse()
}
I saw similar construction in some tutorial, but it gives me error:
我在一些教程中看到了类似的结构,但它给了我错误:
pattern type is incompatible with expected type;
[error] found : object MyFirst
[error] required: MyAbstract
So is there a way to define few different types in on case clause? I think it would make code prettier. As if I will have 5 of them, I will write same code 5 times (calling doSomething()).
那么有没有办法在 on case 子句中定义几种不同的类型?我认为这会使代码更漂亮。好像我将有 5 个,我将编写相同的代码 5 次(调用 doSomething())。
Thanks in advance!
提前致谢!
回答by Faiz
You are missing the parenthesis for your case classes. Case classes without parameter lists are deprecated.
您缺少案例类的括号。不推荐使用没有参数列表的案例类。
Try this:
试试这个:
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()
}
If you have too many params for your case classes and don't like having to write long Foo(_,_,..)patterns, then maybe:
如果您的案例类有太多参数并且不想编写长Foo(_,_,..)模式,那么可能:
x match {
case aOrB @ (_:MyFirst | _:MySecond) => doSomething(aOrB)
case _ => doSomethingElse()
}
Or just:
要不就:
x match {
case _:MyFirst | _:MySecond => doSomething(x) // just use x instead of aOrB
case _ => doSomethingElse(x)
}
But perhaps you just wanted singleton case objects?
但也许你只是想要单例 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()
}

