Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a value from the outer scope when a local member with the same name is present

Tags:

scala

Say I have a trait with a property a:

trait TheTrait {
  def a: String
}

I have a class with a property a too in which I want to instantiate that trait anonymously:

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
  }
}

How can I achieve this?

like image 551
Nikita Volkov Avatar asked Dec 31 '11 07:12

Nikita Volkov


1 Answers

either TheClass.this.a, or give an alias to this in TheClass (calling it self is customary)

class TheClass { self => 
  val a = "abc"
  val traitInstance = new TheTrait {
    def a = self.a   
  }
}
like image 78
Didier Dupont Avatar answered Oct 06 '22 01:10

Didier Dupont