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

前端 未结 8 982
再見小時候
再見小時候 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 20:03

    def defines a method. When you call the method, the method ofcourse runs.

    val defines a value (an immutable variable). The assignment expression is evaluated when the value is initialized.

    lazy val defines a value with delayed initialization. It will be initialized when it's first used, so the assignment expression will be evaluated then.

提交回复
热议问题