Recursive value xxx needs type in Scala

Deadly 提交于 2020-08-02 06:09:54

问题


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 ?


回答1:


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



回答2:


You can specify the type of y specifically and it will compile:

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


来源:https://stackoverflow.com/questions/32227092/recursive-value-xxx-needs-type-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!