Scala recursive type alias error

I have a couple of functions whose only requirement is that it has some kind of collection that is also growing (i.e. it could be a queue, list, PriorityQueue, etc.), so I tried to create the following type alias

type Frontier = Growable[Node] with TraversableLike[Node, Frontier] 

for use with function definitions as follows:

 def apply(frontier: Frontier) = ??? 

but the type alias returns the "Illegal circular reference with Frontier type" error. Is there a way around an illegal circular reference in order to use a type alias or something similar to it?

One solution is to use:

 def apply[F <: Growable[Node] with TraversableLike[Node, F]](f: F) = ??? 

but this seems to add unnecessary verbosity when a function definition does, apparently, the same thing as a type alias. The type is also used elsewhere, so the type alias will greatly increase readability.

+7
source share
1 answer

From section 4.3 specification :

The rules of the definition domain (ยง4) and type parameters (Section 4.6) it is possible that the type name appears in its own binding or in its Right side. However, this is a static error if a type alias is mentioned recursively to the constructor of a particular type.

No, there is no way to do this directly, but you can do the same with the type parameter in the type alias:

 type Frontier[F <: Frontier[F]] = Growable[Int] with TraversableLike[Int, F] 

Now you simply write apply as follows:

 def apply[F < Frontier[F]](frontier: F) = ??? 

Still more detailed than your hypothetical first option, but shorter than writing it all.

You can also just use the legend for the existential type:

 type Frontier = Growable[Node] with TraversableLike[Node, _] 

Now your first apply will work as it is. You just say that there must be some type that is suitable for this slot, but you do not care what it is.

In this case, in particular, is there a reason you are not using Traversable[Node] ? It will perform almost the same thing, and will not be parameterized by the type of representation.

+6
source

All Articles