0

I have an anonymous inner class, and I want to acces the (anonymous) outer class of it in the constructor. So I want to implement this method:

new Outer {
  new Inner {

  }
}

class Outer {

}

class Inner {
  def outerClass: Outer = ???
}
  • It is impossible without stack trace magic. Maybe we can suggest you better solution to your problem? – talex Sep 22 '16 at 14:01
  • I have tried this with implicit parameters, I failed, but maybe it is possible for you? – Bert Becker Sep 22 '16 at 14:45
  • I believe that you trying to solve some other problem by doing this. If it is true, explain it to us. Maybe it is better solution. – talex Sep 22 '16 at 16:25

2 Answers2

2

What speaks against this approach?

new Outer { self =>
  new Inner(self) {

  }
}

class Outer {
}

class Inner[A](outerClass:A) {
  println("CLASS: " + outerClass.getClass)
}
sascha10000
  • 1,245
  • 1
  • 10
  • 22
1

You can do this using implicits easily enough (I assume both Outer and Inner can be modified, but the code using them should look like in the question). Declarations:

class Outer {
  implicit def o: Outer = this
}

class Inner(implicit val outerClass: Outer) {
}

Usage:

new Outer {
  new Inner {
    // can use outerClass here
  }
}

or

new Outer {
  val inner = new Inner {

  }

  // inner.outerClass
}

And I can imagine this being useful for DSLs, but be sure you(r API's users) actually want it first!

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487