Scala和前向引用 [英] Scala and forward references

查看:163
本文介绍了Scala和前向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:





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)
  }

}

空值。在java中。类似的构造由于无效的前向引用而不编译。问题是 - 为什么它在Scala中编译良好?是通过设计,在SLS中描述或只是在2.9.1中的错误?

the following code prints "null". In java. similar construction doesn't compile because of invalid forward reference. The question is - why does it compile well in Scala? Is that by design, described in SLS or simply bug in 2.9.1?

推荐答案

这不是一个错误,当学习Scala。当对象 Omg 初始化时,首先将所有值设置为默认值(在这种情况下为 null ),然后

It's not a bug, but a classic error when learning Scala. When the object Omg is initialized, all values are first set to the default value (null in this case) and then the constructor (i.e. the object body) runs.

要使其正常工作,只需在前面添加 lazy 关键字( a ):

To make it work, just add the lazy keyword in front of the declaration you are forward referencing (value a in this case):

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

这种构造是快速的(值只对所有应用程序运行时初始化一次)和线程安全。

This construction is fast (the values are only initialized once for all application runtime) and thread-safe.

这篇关于Scala和前向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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