我注意到lazy val
多次重复计算(如果例外):
scala> lazy val aaa = {println("calc"); sys.error("aaaa")}
aaa: Nothing = <lazy>
scala> aaa
calc
java.lang.RuntimeException: aaaa
at scala.sys.package$.error(package.scala:27)
at .aaa$lzycompute(<console>:7)
at .aaa(<console>:7)
... 33 elided
scala> aaa
calc
java.lang.RuntimeException: aaaa
at scala.sys.package$.error(package.scala:27)
at .aaa$lzycompute(<console>:7)
at .aaa(<console>:7)
... 33 elided
不应该是这样的:
scala> aaa
calc
java.lang.RuntimeException: Not Initialized!
caused by
java.lang.RuntimeException: aaaa
scala> aaa
java.lang.RuntimeException: Not Initialized!
caused by
java.lang.RuntimeException: aaaa
答案 0 :(得分:5)
在this帖子中,他们非常清楚地解释了Scala编译器如何编译lazy val
。基本上,如果表达式的评估失败,那么lazy val
包含其数据的指示符位信号将不会被设置。
<强> UPDATE1:强>
我认为采用第一种方法的一个原因可能是第二种方法可以通过使用两个lazy val
进行模拟,而不会为底层实现增加多个volatile变量:
scala> lazy val _aaa = Try {println("calc"); sys.error("aaaa")}
_aaa: scala.util.Try[Nothing] = <lazy>
scala> lazy val aaa = _aaa.get
aaa: Nothing = <lazy>
scala> aaa
calc
java.lang.RuntimeException: aaaa
at scala.sys.package$.error(package.scala:27)
at $anonfun$_aaa$1.apply(<console>:10)
at $anonfun$_aaa$1.apply(<console>:10)
at scala.util.Try$.apply(Try.scala:191)
at ._aaa$lzycompute(<console>:10)
at ._aaa(<console>:10)
at .aaa$lzycompute(<console>:11)
at .aaa(<console>:11)
... 33 elided
scala> aaa
java.lang.RuntimeException: aaaa
at scala.sys.package$.error(package.scala:27)
at $anonfun$_aaa$1.apply(<console>:10)
at $anonfun$_aaa$1.apply(<console>:10)
at scala.util.Try$.apply(Try.scala:191)
at ._aaa$lzycompute(<console>:10)
at ._aaa(<console>:10)
at .aaa$lzycompute(<console>:11)
at .aaa(<console>:11)
... 33 elided
<强> UPDATE2:强>
正如@Silly Freak在评论中提出的那样,
scala> lazy val _aaa = Try {println("calc"); sys.error("aaaa")}
_aaa: scala.util.Try[Nothing] = <lazy>
scala> def aaa = _aaa.get
aaa: Nothing
可能会更好,因为我们可以避免使用两个lazy val
。