Black monkey house: Scala lazy value

When val is declared as lazy, he's initialization will be delayed until the first time we have this value for the cost of initializing a larger scene.

lazy example: whether or not to process the observation by using keywords lazy

1, do not use the keyword Lazy

def lazyFun(content:String) = {
   println("lazyFun 得到执行")
   println(content)
 }

val f1 = lazyFun("嘿嘿嘿")
println("f1 变量定义完成")
println(f1)

2, using the lazy keyword

def lazyFun(content:String) = {
   println("lazyFun 得到执行")
   println(content)
 }

lazy val f1 = lazyFun("嘿嘿嘿")
println("f1 变量定义完成")
println(f1)

3, Other Cases

object LazyMain {

  def init(): String = {
    println("init方法执行")
    "嘿嘿嘿,我来了~"
  }

  def main(args: Array[String]): Unit = {
    lazy val msg = init()
    println("lazy方法没有执行")
    println(msg)
  }
}

Reproduced in: https: //www.jianshu.com/p/c5aefe2a4fc1

Guess you like

Origin blog.csdn.net/weixin_34358092/article/details/91182430