假设我有一个具有属性 a
的特征:
trait TheTrait {
def a: String
}
我有一个带有属性 a
的类,我想在其中匿名实例化该特征:
class TheClass {
val a = "abc"
val traitInstance = new TheTrait {
def a = a // I want to assign it to the `a` of TheClass here
// but this way it doesn't work
}
}
我怎样才能实现这个目标?
最佳答案
或者TheClass.this.a
,或者在TheClass
中给this
一个别名(称之为self
)是习惯)
class TheClass { self =>
val a = "abc"
val traitInstance = new TheTrait {
def a = self.a
}
}
关于scala - 当存在同名本地成员时从外部范围访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8687010/