scala中用lazy定义的变量叫做惰性变量,会实现延迟加载。惰性变量只能是不可变的变量。并且只有在调用惰性变量的时候才会被初始化。

 

class Test1 {

}

object Test1 {
  def main(args: Array[String]): Unit = {
    val property  = init();
    println("after init function")
    println(property)
  }
  def init(): Unit = {
    println("init function invoked!");
  }

}
正常非惰性变量的执行结果为:

  init function invoked!
  after init function
  ()

 当property被声明为惰性变量时的代码如下

class Test1 {

}

object Test1 {
def main(args: Array[String]): Unit = {
lazy val property = init();
println("after init function")
println(property)
}
def init(): Unit = {
println("init function invoked!");
}

}
执行结果为:

after init function
init function invoked!
()

相关文章:

  • 2021-09-10
  • 2021-11-22
  • 2021-06-13
  • 2021-09-28
  • 2021-07-12
  • 2021-10-17
  • 2021-07-12
猜你喜欢
  • 2022-01-06
  • 2021-06-22
  • 2021-07-07
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-08-27
相关资源
相似解决方案