Berlin Brown
Berlin Brown

Reputation: 11734

This keyword with scala and anonymous functions/classes

In Java, I could reference the outer instance of a particular class: Sorry, I meant this.

object obj extends SomeOtherClass {
def myMethodOfSomeInstance = {
val uiThread = new SomeClass {
          def run: Unit = {
            chooser.showOpenDialog(SomeOtherClass.this)            
          }
        }
}

... This code does not compile, but on this line, I want to reference the parent instance? How do I do that?

chooser.showOpenDialog(SomeOtherClass.this)

Upvotes: 2

Views: 721

Answers (1)

Moritz
Moritz

Reputation: 14212

You can use a self reference in the enclosing object that you can refer to:

object SomeObject { outer =>
  def myMethodOfSomeInstance = {
    val uiThread = new SomeClass {
      def run: Unit = {
        chooser.showOpenDialog(outer)
      }
    }
  }
}

EDIT: By the way your declaration of the object would have to be object obj extends SomeOtherClass for being valid scala code. You could then also refer to the enclosing object with obj.this.

Upvotes: 4

Related Questions