Scala lazy val caching

In the following example:

def maybeTwice2(b: Boolean, i: => Int) = {
  lazy val j = i
  if (b) j+j else 0
}

      

Why is hi not printed twice when I call this:

maybeTwice2(true, { println("hi"); 1+41 })

      

This example is actually from the book "Functional Programming in Scala" and the reason why "hello" is not printed twice is not convincing enough to me. So just think about it here!

+3


source to share


2 answers


So, i

is this the function that gives the integer on the right? When you call the method you pass b

as true and the if statement executes the first branch.



What happens is what is j

set to i

, and the first time it is later used in a computation, it does that function, prints "hello" and caches the resulting value 1 + 41 = 42

. The second time it is used, the resulting value has already been computed, and therefore the function returns 84, without having to evaluate the function twice because of lazy val j

.

+4


source


This SO answer explores how lazy val is internally implemented. B j + j

, j

is lazy val, which is a function that executes the code you provide to define lazy val, returns an integer and caches it for further calls. So it prints hi

and returns 1+41 = 42

. Then the second is evaluated j

and called the same function. Except for this time, instead of running your code, it fetches the value (42) from the cache. Then two integers are added (return 84).



+3


source







All Articles