lazy val

来源:互联网 发布:如何升级淘宝等级 编辑:程序博客网 时间:2024/05/15 06:38

1. Description

A related scenario to by-name parameters is the case where you want to evaluate an expression once to initialize a value, not repeatedly, but you want to defer that invocation. There are some common scenarios where this is useful:

  1. The expression is expensive (e.g., opening a database connection) and we want to avoid the overhead until the value is actually needed.
  2. Improve startup times for modules by deferring work that isn’t needed immediately.
  3. Sometimes a field in an object needs to be initialized lazily so that other initializations can happen first.

code example

package com.brown/**  * Created by BrownWong on 2016/9/29.  */object Hello {  def main(args: Array[String]): Unit = {    lazy val a: Int = init()    println("Do some things...")    println(a)  }  def init(): Int = {    println("calling init()")    1  }}

output

Do some things...calling init()1

The lazy keyword indicates that evaluation should be deferred until the value is needed.

2. How is a lazy val different from a method call?

In a method call, the body is executed every time the method is invoked. For a lazy val, the initialization “body” is evaluated only once, when the value is used for the first time.

3. Be implemented with a guard

Lazy values are implemented with a guard. When client code references a lazy value, the reference is intercepted by the guard to check if initialization is required. This guard step is really only essential the first time the value is referenced, so that the value is initialized first before the access is allowed to proceed.
Unfortunately, there is no easy way to eliminate these checks for subsequent calls. So, lazy values incur overhead that“eager” values don’t. Therefore, you should only use them when the guard overhead is outweighed by the expense of initialization or in certain circumstances where careful ordering of initialization dependencies is most easily implemented by making some values lazy.


Ref

《Programming Scala》

0 0