当存在具有相同名称的本地成员时,从外部作用域访问值

Nik*_*kov 12 scala

说我有一个属性的特征a:

trait TheTrait {
  def a: String
}
Run Code Online (Sandbox Code Playgroud)

我有一个属性的类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
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Did*_*ont 22

任一TheClass.this.a,或给予一个别名到thisTheClass(呼叫它self是习惯)

class TheClass { self => 
  val a = "abc"
  val traitInstance = new TheTrait {
    def a = self.a   
  }
}
Run Code Online (Sandbox Code Playgroud)