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

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

问题描述

<块引用>

可能的重复:
Scala:前向引用 - 为什么编译这段代码?

object Omg {A级B类(val a:A)私有 val b = 新 B(a)私有 val a = 新 Adef main(args: Array[String]) {打印(b.a)}}

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

解决方案

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

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

object Omg {A级B类(val a:A)私有 val b = 新 B(a)私有惰性 val a = 新 Adef main(args: Array[String]) {打印(b.a)}}

a 然后将根据需要进行初始化.

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

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

}

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?

解决方案

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.

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

Value a will then be initialized on demand.

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

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

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