문제

I needed some recursive structural type in some piece of code using with traits and the structural type as type parameter constraint. It worked fine, but later I learned Scala does not support recursive structural types.

So can someone explain me why this works fine:

scala> trait Test[M[A] <: { def map[B](f: A => B) : M[B] } ] {}
defined trait Test

and this not:

scala> def test[M[A] <: { def map[B](f: A => B) : M[B] } ] = null
<console>:5: error: illegal cyclic reference involving type M
       def test[M[A] <: { def map[B](f: A => B) : M[B] } ] = null
도움이 되었습니까?

해결책

I think this is a glitch in the compiler. The following code exhibits the same behavior as your initial code:

trait Test[M[A] <: { def map: M[A] } ] {}
def test[M[A] <: { def map: M[A] } ] = null

It results in a compile time error: 'illegal cyclic reference'.

And the following code does not (i.e. it compiles fine):

type S[M] = { def map: M }

trait Test[M[A] <: S[M[A]] ] {}
def test[M[A] <: S[M[A]] ] = null

The only difference is that structural typing is applied via a type alias S here.

다른 팁

The first code snippet also throws error in Scala 2.7.7final:

scala> trait Test[M[A] <: { def map[B](f: A => B) : M[B] } ] {}
<console>:4: error: illegal cyclic reference involving type M
       trait Test[M[A] <: { def map[B](f: A => B) : M[B] } ] {}
                                                    ^

Which version of Scala do you use?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top