I noticed that Scala provide lazy vals
. But I don't get what they do.
scala> val x = 15
x: Int = 15
scala> lazy val y = 13
y: Int = <lazy>
scala> x
res0: Int = 15
scala> y
res1: Int = 13
The REPL shows that y
is a lazy val
, but how is it different from a normal val
?
This question is related to
scala
lazy-evaluation
A lazy val is most easily understood as a "memoized (no-arg) def".
Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.
As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.
Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:
http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html
This feature helps not only delaying expensive calculations, but is also useful to construct mutual dependent or cyclic structures. E.g. this leads to an stack overflow:
trait Foo { val foo: Foo }
case class Fee extends Foo { val foo = Faa() }
case class Faa extends Foo { val foo = Fee() }
println(Fee().foo)
//StackOverflowException
But with lazy vals it works fine
trait Foo { val foo: Foo }
case class Fee extends Foo { lazy val foo = Faa() }
case class Faa extends Foo { lazy val foo = Fee() }
println(Fee().foo)
//Faa()
scala> lazy val lazyEight = {
| println("I am lazy !")
| 8
| }
lazyEight: Int = <lazy>
scala> lazyEight
I am lazy !
res1: Int = 8
I understand that the answer is given but I wrote a simple example to make it easy to understand for beginners like me:
var x = { println("x"); 15 }
lazy val y = { println("y"); x + 1 }
println("-----")
x = 17
println("y is: " + y)
Output of above code is:
x
-----
y
y is: 18
As it can be seen, x is printed when it's initialized, but y is not printed when it's initialized in same way (I have taken x as var intentionally here - to explain when y gets initialized). Next when y is called, it's initialized as well as value of last 'x' is taken into consideration but not the old one.
Hope this helps.
Also lazy
is useful without cyclic dependencies, as in the following code:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { val x = "Hello" }
Y
Accessing Y
will now throw null pointer exception, because x
is not yet initialized.
The following, however, works fine:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { lazy val x = "Hello" }
Y
EDIT: the following will also work:
object Y extends { val x = "Hello" } with X
This is called an "early initializer". See this SO question for more details.
A demonstration of lazy
- as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)
// compiler says this is ok when it is lazy
scala> lazy val t: Int = t
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t
java.lang.StackOverflowError
...
// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
val t: Int = t
Source: Stackoverflow.com