Scala 中的“def"与“val"与“lazy val"评估 [英] `def` vs `val` vs `lazy val` evaluation in Scala

查看:31
本文介绍了Scala 中的“def"与“val"与“lazy val"评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是否正确

  • def 每次被访问时都会被评估

  • def is evaluated every time it gets accessed

lazy val 一旦被访问就会被评估

lazy val is evaluated once it gets accessed

val 一旦进入执行范围就被评估?

val is evaluated once it gets into the execution scope?

推荐答案

是的,虽然对于第三个我会说当那个语句被执行时",因为,例如:

Yes, though for the 3rd one I would say "when that statement is executed", because, for example:

def foo() {
    new {
        val a: Any = sys.error("b is " + b)
        val b: Any = sys.error("a is " + a)
    }
}

这给出了 b 为空".b 永远不会被评估并且它的错误永远不会被抛出.但是一旦控制进入块,它就在范围内.

This gives "b is null". b is never evaluated and its error is never thrown. But it is in scope as soon as control enters the block.

这篇关于Scala 中的“def"与“val"与“lazy val"评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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