Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 765
dk14 Avatar asked Nov 01 '22 06:11

dk14


1 Answers

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.

like image 106
Ben Hutchison Avatar answered Nov 15 '22 07:11

Ben Hutchison