lazy function definitions in scala

David K. picture David K. · Aug 25, 2010 · Viewed 20.2k times · Source

I've been learning scala and I gotta say that it's a really cool language. I especially like its pattern matching capabilities and function literals but I come from a javascript, ruby background and one of my favorite patterns in those languages is the lazy function and method definition pattern. An example in javascript is

var foo = function() {
  var t = new Date();
  foo = function() {
    return t;
  };
  return foo();
};

The same code with minor tweaks works in ruby where you just use the singleton object to redefine the method after the computation is performed. This kind of thing comes in really handy when expensive computation are involved and you don't know ahead of time if you are going to need the result. I know that in scala I can use a cache to simulate the same kind of result but I'm trying to avoid conditional checks and so far my experiments have returned negative results. Does anyone know if there is a lazy function or method definition pattern in scala?

Note: The javascript code is from Peter Michaux's site.

Answer

Rex Kerr picture Rex Kerr · Aug 25, 2010

All that complicated code in JavaScript appears to just try to cache the value of the date. In Scala, you can achieve the same thing trivially:

lazy val foo = new Date

And, if don't even want to make a val, but want to call a function that will only execute the expensive code if it needs it, you can

def maybeExpensive(doIt: Boolean, expensive: => String) {
  if (doIt) println(expensive)
}
maybeExpensive(false, (0 to 1000000).toString)  // (0 to 1000000).toString is never called!
maybeExpensive(true, (0 to 10).toString)        // It is called and used this time

where the pattern expensive: => String is called a by-name parameter, which you can think of as, "Give me something that will generate a string on request." Note that if you use it twice, it will regenerate it each time, which is where Randall Schultz' handy pattern comes in:

def maybeExpensiveTwice(doIt: Boolean, expensive: => String) {
  lazy val e = expensive
  if (doIt) {
    println(e)
    println("Wow, that was " + e.length + " characters long!")
  }
}

Now you generate only if you need it (via the by-name parameter) and store it and re-use it if you need it again (via the lazy val).

So do it this way, not the JavaScript way, even though you could make Scala look a lot like the JavaScript.