Scala instanceOf vs模式匹配和复合类型

loading...


0

此示例代码的行为不符合预期 .

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-example:https://scastie.scala-lang.org/ugepOPOtRcu6IenIaw3kAQ

loading...

0回答

No Data

评论

暂时没有评论!