scala lazy關鍵字

scala lazy 加載、 模式匹配case實例

lazy 賴加載

Scala中使用關鍵字lazy來定義惰性變量,實現延遲加載(懶加載)。 惰性變量只能是不可變變量,並且只有在調用惰性變量時,纔會去實例化這個變量。

我們看一下spark源碼中的這段代碼


/** Default properties present in the currently defined defaults file. */
  lazy val defaultSparkProperties: HashMap[String, String] = {
    val defaultProperties = new HashMap[String, String]()
    if (verbose) SparkSubmit.printStream.println(s"Using properties file: $propertiesFile")
    Option(propertiesFile).foreach { filename =>
      Utils.getPropertiesFromFile(filename).foreach { case (k, v) =>
        if (k.startsWith("spark.")) {
          defaultProperties(k) = v
          if (verbose) SparkSubmit.printStream.println(s"Adding default property: $k=$v")
        } else {
          SparkSubmit.printWarning(s"Ignoring non-spark config property: $k=$v")
        }
      }
    }
    defaultProperties
  } 
注意:lazy 修飾的是val變量(不可變)

實例:

class LazyTest() {

  lazy val aaa: mutable.HashMap[String, String] = {
    val value = new mutable.HashMap[String, String]()
    value.put("a", "b")
    value.put("c", "d")
    value.put("e", "f")
    value
  }

  def init: String = {
    println("aaa")
    return ""
  }

}

object LazyTest {
  def main(args: Array[String]): Unit = {
    lazy val value =  new LazyTest().init
//    val value =  new LazyTest().init
    println("bbb")
    value
  }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章