Why is this cyclic reference with a type projection illegal?
Asked Answered
C

1

14

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:

Corella answered 16/7, 2011 at 19:50 Comment(0)
M
16

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]] ...
Mammet answered 16/7, 2011 at 20:55 Comment(1)
Great info, thanks! I was indeed trying to surface the type member.Corella

© 2022 - 2024 — McMap. All rights reserved.