lazy val

Scala中Lazy Val的使用
本文探讨了Scala中Lazy Val的使用场景与实现原理。详细介绍了如何通过Lazy Val来优化模块启动时间,延迟昂贵操作的执行,以及解决初始化依赖顺序问题。通过代码示例展示了Lazy Val的具体应用。

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》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值