dk14
dk14

Reputation: 22374

Why I can't create F-bounded object in Scala

Suppose I have:

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

This doesn't work:

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

But this works:

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

Doing almost (not exactly) same and this works. Any reason?

P.S. And also, what exactly can I do inside such object to force infinte cycle inside the compiler itself?

Upvotes: 5

Views: 155

Answers (1)

Ben Hutchison
Ben Hutchison

Reputation: 2481

As you allude to in your title, the working case class AAA extends A[AAA] is an example of F-bounded polymorphism, which is a recursive type definition where the definition refers to itself. Recursion is fairly common in types, even the humble List is recursive; it's fairly well understood territory.

However, object AAA extends A[AAA.type] is not a recursive type. Here AAA is a value, and your declaration asks the compiler to resolve the reference to a value's type while it is being defined, which is not a capability Scala was designed/intended to have.

Upvotes: 2

Related Questions