Scala 趣题 11 Lazy val 你所不知道的

第二次输出,会得到1吗?


package pzs

object Pz011 extends App {
  var x = 0
  lazy val y = 1/x
  try {
    println(y)
  } catch {
    case _: Throwable => 
      x = 1
      println(y)
  }
}




















解释:


Explanation


One of the most interesting things about lazy values (besides that they defer actual computation) is that they will be recomputed on call if there was an exception at the moment of first access, until some definite value is acquired. So you can use this useful pattern in many situations, for example to handle missing files.

 如果第一次失败,它还会重新计算!

你可能感兴趣的:(scala)