此示例代码的行为与预期不符。
trait A
trait C
class X() {
object B {
def apply(): A = new B{}
}
object BC {
def apply(): A = new B with C {}
}
class B extends A
}
val x1 = new X()
val x2 = new X()
val x1b = x1.B()
//this works
x1b match {
case x2b: x2.B => "X2.B"
case x1b: x1.B => "X1.B"
} //res: X1.B
//this does not test if B is instance from x2???
if(x1b.isInstanceOf[x2.B]) "X2.B" else if(x1b.isInstanceOf[x1.B]) "X1.B" else "" //res: X2.B
val x1bc = x1.BC()
//when matching for compounded types inner class origin is ignored???
x1bc match {
case x2bc: x2.B with C => "X2.BC"
case x1bc: x1.B with C => "X1.BC"
}//res: X2.BC
//does not work
if(x1bc.isInstanceOf[x2.B with C]) "X2.BC" else if(x1bc.isInstanceOf[x1.B with C]) "X1.BC" else "" //res: X2.BC
为什么模式匹配忽略复合类型的内部类类型?
instanceOf为什么完全忽略内部类类型?
经过测试的Scala 2.11和2.12
scastie示例:https://scastie.scala-lang.org/ugepOPOtRcu6IenIaw3kAQ