Reputation: 41
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 = ???
}
Upvotes: 0
Views: 174
Reputation: 170723
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!
Upvotes: 1
Reputation: 1230
What speaks against this approach?
new Outer { self =>
new Inner(self) {
}
}
class Outer {
}
class Inner[A](outerClass:A) {
println("CLASS: " + outerClass.getClass)
}
Upvotes: 2