Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

scala - Why is this cyclic reference with a type projection illegal?

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]] ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...