`def` vs `val` vs `lazy val` evaluation in Scala

前端 未结 8 983
再見小時候
再見小時候 2020-11-30 19:05

Am I right understanding that

  • def is evaluated every time it gets accessed

  • lazy val is evaluated once it gets acce

8条回答
  •  佛祖请我去吃肉
    2020-11-30 19:46

    You are correct. For evidence from the specification:

    From "3.3.1 Method Types" (for def):

    Parameterless methods name expressions that are re-evaluated each time the parameterless method name is referenced.

    From "4.1 Value Declarations and Definitions":

    A value definition val x : T = e defines x as a name of the value that results from the evaluation of e.

    A lazy value definition evaluates its right hand side e the first time the value is accessed.

提交回复
热议问题