Scala lazy function (lazy loading)

Lazy function

  • When the function return value is declared as a lazy type, the execution of the function will be postponed, and the function will be executed only when the value of the function is fetched for the first time.

Code

def sum(x: Int, y: Int): Int = {
    
    
  println("sum函数被执行了...")
  x + y
}

lazy val res: Int = sum(1,2)
// println(res)

note

Lazy cannot modify variables of type var.

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114435745