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 。 当我们需要在创建对象时节省内存开销时,可以使用惰性变量 。 使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值