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 。 当我们需要在创建对象时节省内存开销时,可以使用惰性变量 。 使用lazy关键字,可以暂停变量的初始化,直到在代码中首次使用或访问该变量为止。
程序来说明懒惰的瓦尔 (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.
与代码中一样,该块在调用第一个print语句之后初始化。 newBlock的打印语句将仅打印一次。 在第二个调用中,它将返回字符串“ Hello!”。 并且不打印任何内容。
翻译自: https://www.includehelp.com/scala/lazy-val.aspx