lazy val memoization

27 views
Skip to first unread message

des.m...@gmail.com

unread,
Apr 10, 2018, 11:19:24 AM4/10/18
to scala-functional
Hi

Based on my understanding of the explanation of lazy val memoization in section 5.2.1, I would have thought that if I define the following function:

    def func(i: => Int): Unit = {
        lazy val cached = {
            println("Calculating")
            i * i
        }
        cached
    }

And then made the following calls:

func(3)
func(3)

that my lazy evaluation should only happen once? - as the function is getting called with the same parameter the second time. But this is not the case when I test. Could someone explain what I am missing here?

Thanks
Des

Brian Maso

unread,
Apr 10, 2018, 11:30:32 AM4/10/18
to scala-fu...@googlegroups.com
The lazy val is declared as a member of the function, so each time the function is called there is a new lazy val being memoized.

Brian Maso

--
You received this message because you are subscribed to the Google Groups "scala-functional" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-functional+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Best regards,
Brian Maso
(949) 395-8551
Follow me: @bmaso
br...@blumenfeld-maso.com

des.m...@gmail.com

unread,
Apr 10, 2018, 2:09:46 PM4/10/18
to scala-functional
Ah OK. So I am guessing I misunderstood section 5.2.1. The "cons" function is only ever called once in this scenario?

Adam Mackler

unread,
Apr 10, 2018, 4:03:08 PM4/10/18
to scala-functional
The value cached is defined inside the definition of the method func(), so everytime you invoke func() it defines a new local Int named cached.  Change your code to this:

def func(i: => Int): Unit = {
  lazy val cached = {
    println("Calculating")
    i * i
  }
  println(cached)
  println(cached)
  println(cached)
}

and you will see that it prints "Calculating" only once each time you invoke func(), even though func() is now accessing cached three times.

Steven Parkes

unread,
Apr 10, 2018, 5:22:36 PM4/10/18
to scala-fu...@googlegroups.com
And, FWIW, one thing we just noticed is that the lazy implementation for this case takes the lock on the object that contains this val even though the scope of this particular value is note the object scope, at least in 2.11.something.

In our case, we had a lot of lock contention that we weren't expecting/aware of.

Our conclusion was that lazy locals are of _very_ limited and mostly to be avoided.

--
Reply all
Reply to author
Forward
0 new messages