Lazy val

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 / 0
num: 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}
x
x: Int = 20

scala> x
res1: Int = 20
scala>

This works and, later on, you can access the value of variable x when required. These are just a few examples of using lazy val concepts. Interested readers should access this page for more details: https://blog.codecentric.de/en/2016/02/lazy-vals-scala-look-hood/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.190