本文介绍了如何访问“覆盖"? Scala的内部阶级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个特征,一个扩展了另一个,每个具有一个内部类,一个扩展了另一个,具有相同的名称:
I have two traits, one extending the other, each with an inner class, one extending the other, with the same names:
trait A {
class X {
def x() = doSomething()
}
}
trait B extends A {
class X extends super.X {
override def x() = doSomethingElse()
}
}
class C extends B {
val x = new X() // here B.X is instantiated
val y = new A.X() // does not compile
val z = new A.this.X() // does not compile
}
如何访问C
类主体中的A.X
类?重命名B.X
不隐藏A.X
不是首选方法.
How do I access A.X
class in the C
class's body? Renaming B.X
not to hide A.X
is not a preferred way.
让事情有点复杂,在这种情况下,我遇到了这个问题,即特征具有类型参数(在此示例中未显示).
To make things a bit complicated, in the situation I have encountered this problem the traits have type parameters (not shown in this example).
推荐答案
trait A {
class X {
def x() = "A.X"
}
}
trait B extends A {
class X extends super.X {
override def x() = "B.X"
}
}
class C extends B {
val self = this:A
val x = new this.X()
val y = new self.X()
}
scala> val c = new C
c: C = C@1ef4b
scala> c.x.x
res0: java.lang.String = B.X
scala> c.y.x
res1: java.lang.String = A.X
这篇关于如何访问“覆盖"? Scala的内部阶级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!