Search code examples
scalathunk

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 it like:

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

This example is actually from the book "Functional Programming in Scala" and the reason given as why "hi" not getting printed twice is not convincing enough for me. So just thought of asking this here!


Solution

  • So i is a function that gives an integer right? When you call the method you pass b as true and the if statement's first branch is executed.

    What happens is that j is set to i and the first time it is later used in a computation it executes the function, printing "hi" and caching the resulting value 1 + 41 = 42. The second time it is used the resulting value is already computed and hence the function returns 84, without needing to compute the function twice because of the lazy val j.