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

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

问题描述

我是正确的理解

    每次访问
  • def都会对其进行评估

  • def is evaluated every time it gets accessed

lazy val就会对其求值

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

val is evaluated once it gets into the execution scope?

推荐答案

是的,尽管对于第3条,我会说该语句执行时",因为,例如:

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 is null".永远不会评估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 vs val vs lazy val评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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