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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With