递归值 xxx 需要在 Scala 中输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32227092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive value xxx needs type in Scala
提问by Jay
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 Awithout a type declaration, the code won't compile.
我很困惑为什么 Scala 会抱怨这段代码。我有两个相互依赖的类。当我尝试创建一个A没有类型声明的新实例时,代码将无法编译。
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 ywhen I declared as new A?
为什么编译器不知道y我声明为时的类型new A?
采纳答案by Mifeet
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 ywhich is (at this moment) still of unknown type. Thus the compiler detects a cycle "type of ydependes on type of y" and fails.
要推断 的类型y,编译器必须首先确定赋值右侧的值的类型。在评估右手的类型时,它遇到对y(此时)仍然是未知类型的变量的引用。因此,编译器检测到循环“类型y依赖于类型y”并失败。
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 yand succeeds.
在第二个示例中,这种情况不会发生,因为在评估 type of 时new A(new B(y)),它已经知道了 of 的类型y并且成功了。
Edit: when the type of recursively used variable yneeds to include a mixed-in trait, it can be declared like this:
编辑:当递归使用的变量类型y需要包含混合特征时,可以这样声明:
val y : A with Mixin = new A(new B(y)) with Mixin
回答by Chirlo
You can specify the type of yspecifically and it will compile:
您可以具体指定类型,y它会编译:
val y : A = new A(new B(y))

