July 9, 2008

lazy val

If you want a field or local variable to be initialized only when it's required (that is, accessed/used for the first time), you want a lazy val.

Details and debate on this feature's implementation can be found on the Scala User mailing list, but perhaps a better resource is this post that preceded the feature's release from a developer at EPFL (Scala's home).

2 comments:

Robey said...

So far, I've never used (or felt like I needed to use) "lazy" in a place where I couldn't otherwise use a "=>" param. I'm not sure if this means anything about scala, or just indicates the way I think.

Jorge Ortiz said...

Robey,

There's actually an important difference between lazy vals and thunk (=>) parameters. Lazy vals are evaluated once (the first time they are references) and cached (for subsequent references). Thunk parameters are evaluated every time they are referenced (kind of like 'def'). If you want a lazy parameter to a function that is cached, you can use a combination of thunks and lazy vals.

def fn[T](_p: => T) = {
lazy val p = _p
// from now on make sure to reference p and not _p
}