Search code examples
scalapath-dependent-typeself-type

Accessing values from path-dependent type mixin


Is it possible to access values in the outer trait from an inner trait mixin? i.e.:

trait Outer {
  val foo
  trait Inner
}

trait InnerMixin { this: Outer#Inner =>
  def bar {
    // how can I access 'foo' here? smth like Outer.this.foo
  }
}

thanks


Solution

  • As you will be able to mix your InnerMixin only inside some extension of outer, maybe you could define it inside an Outer mixin, this way

    trait Outer {
    
      val foo: Int
    
      trait Inner
    }
    
    trait OuterMixin  { this: Outer =>
    
      trait InnerMixin  { this: Inner =>
        def extension = OuterMixin.this.foo
      }
    }
    
    class ActualOuter extends Outer with OuterMixin {
      val foo = 12
      class ActualInner extends Inner with InnerMixin {
    
      }
    
    }
    

    Note : most of the time, you do not need a self type and you can do just OuterMixin extends Outer and InnerMixin extends Inner.