Scala Lazy 惰性加载
- 原写法;
def main(args: Array[String]): Unit = { val result: Int = sum(13, 47) println("1. 函数调用") println("2. result = " + result) println("4. result = " + result) } def sum(a: Int, b: Int): Int = { println("3. sum调用") a + b }
- 输出
- sum调用 - 函数调用 - result = 60 - result = 60
- Lazy 用法
def main(args: Array[String]): Unit = { lazy val result: Int = sum(13, 47) println("1. 函数调用") println("2. result = " + result) println("4. result = " + result) } def sum(a: Int, b: Int): Int = { println("3. sum调用") a + b }
- 输出
1. 函数调用 3. sum调用 2. result = 60 4. result = 60