July 2017
Intermediate to advanced
796 pages
18h 55m
English
The main characteristic of a lazy val is that the bound expression is not evaluated immediately, but once on the first access. Here's where the main difference between val and lazy val lies. When the initial access happens, the expression is evaluated and the result is bound to the identifier, the lazy val. On subsequent access, no further evaluation occurs, instead, the stored result is returned immediately. Let's see an interesting example:
scala> lazy val num = 1 / 0num: Int = <lazy>
If you look at the preceding code in Scala REPL, you will notice that the code runs very well without throwing any errors, even though you divided an integer with 0! Let's see a better example:
scala> val x = {println("x") 20}xx: Int = 20scala> x ...Read now
Unlock full access