Scala:模式匹配类型但排除特定子类型?
Scala: Pattern match on type but exclude specific subtypes?
例如,如果我有一个混凝土底座 class 和一个子class:
class A
class B extends A
我有兴趣匹配 A
的实例,这些实例不是 B
.
的实例
可以采用以下方法:
// Short-circuit
x match {
case _: B => ()
case _: A => println("Type A and not B")
case _ => ()
}
// Using isInstanceOf
x match {
case a: A if !a.isInstanceOf[B] => println("Type A and not B")
case _ => ()
}
但是还有更多的东西吗idiomatic/succinct/cleaner?谢谢
您可以定义自定义提取器
object ANotB {
def unapply(a: A): Option[A] = a match {
case _: B => None
case _ => Some(a)
}
}
x match {
case ANotB(a) => ???
}
例如,如果我有一个混凝土底座 class 和一个子class:
class A
class B extends A
我有兴趣匹配 A
的实例,这些实例不是 B
.
可以采用以下方法:
// Short-circuit
x match {
case _: B => ()
case _: A => println("Type A and not B")
case _ => ()
}
// Using isInstanceOf
x match {
case a: A if !a.isInstanceOf[B] => println("Type A and not B")
case _ => ()
}
但是还有更多的东西吗idiomatic/succinct/cleaner?谢谢
您可以定义自定义提取器
object ANotB {
def unapply(a: A): Option[A] = a match {
case _: B => None
case _ => Some(a)
}
}
x match {
case ANotB(a) => ???
}