Why can't I create an F-restricted object in Scala

Suppose I have:

trait A[AA <: A[AA]] //or even just ` trait A[AA] 

This does not work:

 scala> object AAA extends A[AAA.type] <console>:8: error: illegal cyclic reference involving object AAA object AAA extends A[AAA.type] ^ 

But it works:

 scala> class AAA extends A[AAA]; object AAA extends AAA defined class AAA defined module AAA 

Doing almost (not quite) the same, and it works. Any reason?

PS And also, what exactly can be done inside such an object to force the infinte loop inside the compiler itself?

+5
source share
1 answer

As you hint in your title, the working example class AAA extends A[AAA] is an example of F-constrained polymorphism , which is a recursive type where the definition refers to itself. Recursion is quite common in types, even a modest List is recursive ; this is a pretty well-understood territory.

However, object AAA extends A[AAA.type] not a recursive type. Here AAA is the value, and your ad asks the compiler to allow a reference to the type of value during its definition, which is not a Scala feature ./

+2
source

All Articles