Jay Jay - 19 days ago 10
Scala Question

Recursive value xxx needs type in Scala

I am confused about why Scala is complaining about this code. I have two classes which depend on each other. When I try to create a new instance of

A
without a type declaration, the code won't compile.

class A( b:B ) {

}

class B( a:A ){

}

val y = new A ( new B( y ) ); // gives recursive value y needs type

val z:A = new A ( new B( y ) ); // ok


Why does the compiler does not know the type of
y
when I declared as
new A

?

Answer

To infer the type of y, the compiler must first determine the type of value on the right side of assignment. While evaluating right hand's type, it encounters reference to variable y which is (at this moment) still of unknown type. Thus the compiler detects a cycle "type of y dependes on type of y" and fails.

In the second example, this situation doesn't occur because when evaluating type of new A(new B(y)), it already knows the type of y and succeeds.

Edit: when the type of recursively used variable y needs to include a mixed-in trait, it can be declared like this:

val y : A with Mixin = new A(new B(y)) with Mixin