Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala lazy val caching

Tags:

scala

thunk

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!

like image 299
joesan Avatar asked Dec 02 '25 03:12

joesan


1 Answers

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.

like image 181
Johan S Avatar answered Dec 03 '25 18:12

Johan S