val strVal = scala.io.Source.fromFile("test.txt").mkString //在strVal被定義的時候獲取值,若是test.txt不存在,直接報異常 lazy val strLazy = scala.io.Source.fromFile("test.txt").mkString //在strLazy第一次被使用的時候取值,若是test.txt不存在,不使用strLazy是不會報異常的,第一次訪問strLazy的時候報異常 def strDef = scala.io.Source.fromFile("test.txt").mkString //每次使用的時候都從新取值
若是一開始test.txt內容是"a",定義好以後,將test.txt內容改成"ab",則strVal == "a", strLazy == "ab",strDef == "ab"。再將test.txt內容改成"abc",則strVal == "a", strLazy == "ab",strDef == "abc"。再修改test.txt的內容,strVal和strLazy都不會改變,而strDef每次都更新。
scala