Scala懒惰瓦尔
Scala | 懶惰的瓦爾 (Scala | lazy val)
Scala programming language allows the user to initialize a variable as a lazy val. A lazy variable is used when we need to save memory overheads while object creation. Using the lazy keyword, you can halt the initialization of the variable until the time it is first used or accessed in the code.
Scala編程語言允許用戶將變量初始化為惰性val 。 當(dāng)我們需要在創(chuàng)建對象時(shí)節(jié)省內(nèi)存開銷時(shí),可以使用惰性變量 。 使用lazy關(guān)鍵字,可以暫停變量的初始化,直到在代碼中首次使用或訪問該變量為止。
程序來說明懶惰的瓦爾 (Program to illustrate lazy val)
object myObject { def main(args:Array[String]) { lazy val newBlock = { println ("This will be printed only in case of first initialization.") "Hello!"} println("The block is not initialized yet!")println("First Call : ")println(newBlock)println("Second Call : ")println(newBlock) } }Output
輸出量
The block is not initialized yet! First Call : This will be printed only in case of first initialization. Hello! Second Call : Hello!As in the code, the block is initialized after the first print statement when it is called. The print statement of the newBlock will be printed only once. In the second call, it will return the string "Hello!" and does not print anything.
與代碼中一樣,該塊在調(diào)用第一個(gè)print語句之后初始化。 newBlock的打印語句將僅打印一次。 在第二個(gè)調(diào)用中,它將返回字符串“ Hello!”。 并且不打印任何內(nèi)容。
翻譯自: https://www.includehelp.com/scala/lazy-val.aspx
總結(jié)
- 上一篇: linux 文件浏览器_浏览Linux文
- 下一篇: strspn函数php,php strs