Search code examples
scalaabstract-typeself-type

Self-type cannot access type member


Given a trait with type parameter, and one with abstract type member:

trait Foo[A] {
  def schoko(f: A) : Unit
}
trait Bar {
  type A
  def foo: Foo[A]
}

trait X

trait ConcreteBar extends Bar {
  final type A = X
}

Is there any change to get any of the following working:

trait Mixin extends ConcreteBar {
  _: Foo[A] => // "not found: type A"
  def foo = this
}

trait Mixin[A] extends Bar {
  _: Foo[A] =>
  def foo = this // "found: Mixin[A] with Foo[A]   required: Foo[Mixin.this.A]"
}

trait Mixin[A1] extends ConcreteBar {
  _: Foo[A1] =>
  type A = A1  // "error: overriding type A in trait ConcreteBar, which equals X"
  def foo = this
}

Solution

  • Using the # syntax for accessing the type A seems to work:

    trait Mixin extends ConcreteBar {
       _: Foo[ ConcreteBar#A ] =>
       def foo = this
    }
    

    It seems that the members of ConcreteBar are not in scope for the self-type declaration, so you have to reference the type explicitly.