简体   繁体   中英

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!

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 .

This SO answer explores how a lazy val is internally implemented. In j + j , j is a lazy val, which amounts to a function which executes the code you provide for the definition of the lazy val, returns an integer and caches it for further calls. So it prints hi and returns 1+41 = 42 . Then the second j gets evaluated, and calls the same function. Except this time, instead of running your code, it fetches the value (42) from the cache. The two integers are then added (returning 84).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM