惰性 val 有什么作用? [英] What does a lazy val do?

查看:26
本文介绍了惰性 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 表明 y 是一个lazy val,但是它和普通的 val 有什么不同?

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

推荐答案

它们的区别在于,val 在定义时执行,而 lazy val第一次访问时执行.

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天全站免登陆