Sunday 28 June 2015

Defining a Field as Lazy in Scala

Defining a field as lazy is a useful approach when the field might not be accessed in the normal processing of your algorithms, or if running the algorithm will take a long time, and you want to defer that to a later time.


trait Foo {
 
 val value: Int
 lazy val inverse = 1.0/value
 
 lazy val text =
    io.Source.fromFile("/etc/passwd")
    .getLines.foreach(println)

//println(inverse)
}

object Test extends Foo {
  val value = 10
  println("inverse =" + inverse) 

}


lazy only helps inverse if the println statement is not used in Foo.
If a val is lazy, make sure all uses of the val are also as lazy as possible.

No comments:

Post a Comment