Scala 和转发引用

标签 scala reference compilation

Possible Duplicate:
Scala: forward references - why does this code compile?

object Omg {

  class A

  class B(val a: A)

  private val b = new B(a)

  private val a = new A

  def main(args: Array[String]) {
    println(b.a)
  }

}

以下代码打印“null”。在java中。由于前向引用无效,类似的构造无法编译。问题是 - 为什么它在 Scala 中编译得很好?这是设计使然、SLS 中描述的还是 2.9.1 中的错误?

最佳答案

这不是一个bug,而是学习Scala时的一个经典错误。当对象 Omg 初始化时,所有值首先设置为默认值(在本例中为 null),然后运行构造函数(即对象主体)。

要使其正常工作,只需在您要前向引用的声明前面添加 lazy 关键字(在本例中为值 a):

object Omg {

  class A

  class B(val a: A)

  private val b = new B(a)

  private lazy val a = new A

  def main(args: Array[String]) {
    println(b.a)
  }
}

a 将根据需要进行初始化。

这种构造速度很快(所有应用程序运行时的值仅初始化一次)并且是线程安全的。

关于Scala 和转发引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14237033/

相关文章:

scala - 在scala 2.13中,为什么有时无法显式调用类型类?

linux - Linux源码包如何在IDE中以项目的形式打开?

linux - 无法让 NTP 交叉编译到 ARM

scala - 玩!斯卡拉 : How to disable actor modules loaded at the start of the application when testing?

scala - 在 Scala 中使用类型类模式对性能有什么影响

c++ - const & 指的是非 volatile 变量。变量发生变化。更改是否会使 const & 无效?

可空引用的 C++ 惯用方式

c - 添加函数调用如何在链接时导致其他符号变得未定义?

scala - def没有参数

pointers - 在 Golang 中取消引用指向同一类型的指针变量而无需引用