最简单的方法是在外部类主体中指定this
声明,以便为每个类定义唯一的名称。但我希望在不修改外部类的情况下编写访问权限。
代码示例:
trait Test {
def z = new Test {
val a = 1
def y = new Test {
val a = false
def x = new Test {
val b = 2 * a
}
}
}
}
在定义val b
时,我希望访问outer.outer.a
,而不仅仅是外部。a
如何指定匿名类的this
?如果是Named
,我可以写Named.this
,但是匿名类没有名字。
发布于 2017-07-22 03:14:30
这可以通过self types来实现
trait Test { greatGrandparent =>
def z = new Test { grandparent =>
val a = 1
def y = new Test { parent =>
val a = false
def x = new Test {
val b = 2 * grandparent.a
}
}
}
}
https://stackoverflow.com/questions/45242117
复制相似问题