Lazy declaration
Before learning more about the lazy
keyword or lazy evaluation, let's talk about why we need it and exactly what it is. Just how beneficial lazy evaluation is can be explained with a few lines, or a few pages, but for our understanding let's have a one liner.
Lazy evaluation lets you write your code in a way where the order of evaluation doesn't matter. It also saves you some time, by only evaluating expressions that you need. It's like so many complex evaluations, that exists in your code, but never evaluation dues to a certain.The last line is only possible due to the concept of lazy evaluation. In Scala, you can declare a value as lazy
. Let's take an example. Try the following in the Scala REPL:
scala> lazy val v = 1 v: Int = <lazy> scala> val z = 1 z: Int = 1
Here, when we assigned a value of 1
to our val v
, the REPL gave us the Int
type and the value as <lazy>
, and for the val z
we got 1
. Why this happened is because of the lazy
declaration. In...