懒惰的val做什么? [英] What does a lazy val do?

查看:122
本文介绍了懒惰的val做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Scala提供了lazy vals.但是我不知道他们怎么做.

I noticed that Scala provide lazy vals. But I don't get what they do.

scala> val x = 15
x: Int = 15

scala> lazy val y = 13
y: Int = <lazy>

scala> x
res0: Int = 15

scala> y
res1: Int = 13

REPL 显示ylazy val,但是与普通的val有何不同?

The REPL shows that y is a lazy val, but how is it different from a normal val?

推荐答案

它们之间的区别在于,val在定义时执行,而lazy val在首次访问时执行. /p>

The difference between them is, that a val is executed when it is defined whereas a lazy val is executed when it is accessed the first time.

scala> val x = { println("x"); 15 }
x
x: Int = 15

scala> lazy val y = { println("y"); 13 }
y: Int = <lazy>

scala> x
res2: Int = 15

scala> y
y
res3: Int = 13

scala> y
res4: Int = 13

与方法(用def定义)相反,lazy val会执行一次,然后再也不会执行.当操作需要很长时间才能完成并且不确定是否以后使用时,此功能很有用.

In contrast to a method (defined with def) a lazy val is executed once and then never again. This can be useful when an operation takes long time to complete and when it is not sure if it is later used.

scala> class X { val x = { Thread.sleep(2000); 15 } }
defined class X

scala> class Y { lazy val y = { Thread.sleep(2000); 13 } }
defined class Y

scala> new X
res5: X = X@262505b7 // we have to wait two seconds to the result

scala> new Y
res6: Y = Y@1555bd22 // this appears immediately

在这里,当从不使用值xy时,仅x会不必要地浪费资源.如果我们假设y没有副作用,并且我们不知道它被访问的频率(永远,一次,数千次),则将其声明为def是没有用的,因为我们不想执行它几次.

Here, when the values x and y are never used, only x unnecessarily wasting resources. If we suppose that y has no side effects and that we do not know how often it is accessed (never, once, thousands of times) it is useless to declare it as def since we don't want to execute it several times.

如果您想知道lazy vals的实现方式,请参见问题.

If you want to know how lazy vals are implemented, see this question.

这篇关于懒惰的val做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆