Scala’s lazy arguments: How do they work?

Call-by-name arguments are called every time you ask for them. Lazy vals are called the first time and then the value is stored. If you ask for it again, you’ll get the stored value.

Thus, a pattern like

def foo(x: => Expensive) = {
  lazy val cache = x
  /* do lots of stuff with cache */
}

is the ultimate put-off-work-as-long-as-possible-and-only-do-it-once pattern. If your code path never takes you to need x at all, then it will never get evaluated. If you need it multiple times, it’ll only be evaluated once and stored for future use. So you do the expensive call either zero (if possible) or one (if not) times, guaranteed.

Leave a Comment