如何通过显式名称空间访问内部类?
问题描述:
trait Base
{
val widget = new Widget {}
trait Widget
}
trait Child1 extends Base
{
override val widget = new Widget {}
trait Widget extends super.Widget
}
trait Child2 extends Base
{
override val widget = new Widget {}
trait Widget extends super.Widget
}
class Sample extends Child1 with Child2
{
override val widget = // Here be dragons
}
有什么方法可以在Sample中正确组成小部件吗?如果Child1#Widget和Child2#Widget具有可分辨的名称,它工作正常,但我很好奇它是否可以像这样访问它们。如何通过显式名称空间访问内部类?
我与new Child1#Widget with Child2#Widget
失败: “不是合法的前缀构造”
或
override val widget =
{
val a = this: Child1
val b = this: Child2
new a.Widget with b.Widget {}
}
“非法继承:继承特质的Widget不同类型实例”
答
您可能试试这个:
class Sample extends Child1 with Child2 {
override val widget = new Widget {}
trait Widget extends super[Child1].Widget with super[Child2].Widget
}
或者只是:
class Sample extends Child1 with Child2 {
override val widget = new super[Child1].Widget with super[Child2].Widget {}
}
对于为什么这种方法不能使用包裹限定符的一个旁注:https://issues.scala-lang.org/browse/SI-1915 – Taig 2014-11-16 19:49:42