You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
traitA {
caseclassB(i: Int)
}
classCextendsA {
def!(a:Any) = a match {
caseB(0) => println("never be here")
caseb: B=> println("never be here")
case x => println(s"Oops, received $x")
}
}
classDextendsA {
newC!B(0)
}
newD
上面代码在 scala REPL 中运行, 打印输出的结果是Oops, received B(0), 问题就出来了:
class C extends AnyRef with A {
def <init>(): C = {
C.super.<init>();
()
};
def !(a: Any): Unit = a match {
case (i: Int)C.this.B(0) => scala.this.Predef.println("never be here")
case (b @ (_: C.this.B)) => scala.this.Predef.println("never be here")
case (x @ _) => scala.this.Predef.println(scala.StringContext.apply("Oops, received ", "").s(x))
}
};
class D extends AnyRef with A {
def <init>(): D = {
D.super.<init>();
()
};
new C().!(D.this.B.apply(0))
}
在new C ! B(0)中B的类型是D.this.B, 而在C.!(a: Any)的match中B的类型都是C.this.B
上面代码在 scala REPL 中运行, 打印输出的结果是
Oops, received B(0)
, 问题就出来了:问题的答案可以从
scalac -Xprint:typer
的结果中找到:在
new C ! B(0)
中B
的类型是D.this.B
, 而在C.!(a: Any)
的match
中B
的类型都是C.this.B
那么答案也就很明确了, 引用之 @hongjiang 的论断:
因此, 在实际应用中, 请谨慎使用这种用法, 除非你有特别好的理由
进一步的思考: Scala 编译器是如何实现的呢?
答案在这里, 你找找看:)
The text was updated successfully, but these errors were encountered: