1. 程式人生 > >Scala 之 關鍵字 lazy

Scala 之 關鍵字 lazy

先看一個示例

scala> val a = { println("I'am a"); "aaa"}
I'am a
a: String = aaa

scala> a
res8: String = aaa

scala> lazy val a = { println("I'am a"); "aaa"}
a: String = <lazy>

scala> a
I'am a
res9: String = aaa

Assume we have the following declaration.

final class LazyCell {
  lazy val value = <RHS>
}

Here is an example of a manually written implementation equivalent to what the compiler currently does:

final class LazyCell {
  @volatile var bitmap_0: Boolean = false
  var value_0: Int = _
  private def value_lzycompute(): Int = {
    this.synchronized {
      if (!bitmap_0) {
        value_0 = <RHS>
        bitmap_0 = true
      }
    }
    value_0
  }
  def value = if (bitmap_0) value_0 else value_lzycompute()
}