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:
- The expression is expensive (e.g., opening a database connection) and we want to avoid the overhead until the value is actually needed.
- Improve startup times for modules by deferring work that isn’t needed immediately.
- 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》
- lazy val
- val 和 lazy val的区别
- scala 中的def/val/lazy val/的区别,call-by-value/call-by-name
- scala def/val/lazy val区别以及call-by-name和call-by-value
- !!val
- lazy
- lazy
- jquery val() $("#sss").val();
- $("id").val()
- 【javascript】val()
- Hibernate Lazy
- lazy TLB
- Lazy Monday!
- Lazy me
- lazy总结
- hibernate---->lazy
- Lazy initialization
- lazy load
- 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'tb_MyInvoices' 中的标识列插入显
- Ubuntu设置root登陆
- 微软已经不再需要Windows了
- POJ 2104 K-th Number
- MFC显示图片过大,拖动滚动条时不正常处理方法
- lazy val
- 值得收藏!Office 2016 KMS激活密钥公布
- php foreach用法
- 安规认证的测试项目(工程师必须知道的知识)
- Mysql中类似于nvl()函数的ifnull()函数
- AndroirStudio关于gradle的配置
- android自定义对话框(AlertDialog)
- Android Alert Dialog点击按钮对话框不关闭
- linux下各目录的作用