Recursive value xxx needs type in Scala

前端 未结 2 1425
暖寄归人
暖寄归人 2021-02-18 22:21

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

2条回答
  •  暖寄归人
    2021-02-18 23:09

    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
    

提交回复
热议问题