相关疑难解决方法(0)

Scala多种类型模式匹配

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

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()
}
Run Code Online (Sandbox Code Playgroud)

所以我想写一些类似的东西:

x match {
 case a @ (MyFirst | MySecond) => doSomething()
 case _ => doSomethingElse()
}
Run Code Online (Sandbox Code Playgroud)

我在一些教程中看到了类似的构造,但它给了我错误:

pattern type is incompatible with expected type;
[error]  found   : object MyFirst …
Run Code Online (Sandbox Code Playgroud)

types scala pattern-matching

66
推荐指数
1
解决办法
5万
查看次数

标签 统计

pattern-matching ×1

scala ×1

types ×1