Search code examples
scalascala-2.9path-dependent-type

How can I override a method with a dependent return type?


I'm having trouble in Scala 2.9.2 implementing a method which declares a dependent return type. The following code

object DependentTypesQuestion {
  def ??? = throw new UnsupportedOperationException
  trait X {
    trait Y
  }
  trait Z {
    def z(x: X): x.Y
  }
  object Z extends Z {
    override def z(x: X): x.Y = ???
  }
}

under 2.9.2 produces the following error message during compilation:

overriding method z in trait Z of type (x: DependentTypesQuestion.X)x.Y;  method z has incompatible type

In 2.10.0-M4 the problem seems to have been fixed, but unfortunately my project is tied to 2.9 for now.

Is it possible to work around this issue in 2.9.2?

(Alternatively, is there any prospect of a 2.9.3 which would include the backported fix from 2.10?)


Solution

  • If you're really stuck with 2.9.x then the following might be a workaround for you,

    object DependentTypesQuestion {
      def ??? = throw new UnsupportedOperationException
      trait X {
        trait Y
      }
      trait Z[D[_ <: X with Singleton]] {
        def z[T <: X with Singleton](x: T): D[T]
      }
    
      type Dep[T <: X with Singleton] = T#Y
    
      object Z extends Z[Dep] {
        override def z[T <: X with Singleton](x: T): x.Y = ???
      }
    }