递归值 xxx 需要在 Scala 中输入 [英] Recursive value xxx needs type in Scala

查看:33
本文介绍了递归值 xxx 需要在 Scala 中输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么 Scala 会抱怨这段代码.我有两个相互依赖的类.当我尝试在没有类型声明的情况下创建 A 的新实例时,代码将无法编译.

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

当我声明为new A时,为什么编译器不知道y的类型?

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

推荐答案

要推断 y 的类型,编译器必须首先确定赋值右侧的值的类型.在评估右手的类型时,它遇到对变量 y 的引用,该变量(此时)仍然是未知类型.因此,编译器检测到循环y 的类型取决于 y 的类型"并失败.

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.

在第二个例子中,这种情况不会发生,因为在评估 new A(new B(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 y and succeeds.

编辑:当递归使用的变量y的类型需要包含一个mixed-in trait时,可以这样声明:

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

这篇关于递归值 xxx 需要在 Scala 中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆