The following pseudo-Scala yields an "illegal cyclic reference" error:
trait GenT[A]
trait T extends GenT[T#A] {
type A
}
Questions: Why is this illegal? Is there a fundamental problem with soundness, or is it a limitation of the Scala type system? Is there a work-around?
My intent is to create a trait T
with a type member A
that can be lifted on demand to a type parameter via the super-trait GenT[A]
. One application might be the expression of constraints, for example
def foo[A, S1 <: GenT[A], S2 <: GenT[A]] ...
This could be used as if it were def foo[S1 <: T, S2 <:T] ...
with the constraint that S1#A == S2#A
.
If the technique were possible, it might also help for the question: How to specialize on a type projection in Scala?
Note: I could use GenT
instead of T
everywhere, but I'm trying to avoid that because it would cause lots of type parameters to spread across all my code "infectiously".
The two questions below seem similar but are about a different type of cyclic reference:
In your initial example you can break the cycle by introducing an auxiliary type inbetween GenT[A] and T,
trait GenT[A]
trait TAux { type A }
trait T extends TAux with GenT[TAux#A]
But from your motivating example I don't think you need to go down this route. The constraint you're after can be expressed directly using a refinement,
trait T { type A }
def foo[A0, S1 <: T { type A = A0 }, S2 <: T { type A = A0 }] ...
Also bear in mind that you can surface a type member as a type parameter via a type alias,
trait T { type A }
type TParam[A0] = T { type A = A0 }
def foo[A0, S1 <: TParam[A0], S2 <: TParam[A0]] ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With