scalascala-reflectscala-implicits

Scala: get outer class from inner class in constructor


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

Solution

  • 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!