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).
Learning Scala. The hard way.
lazy val
.
2 comments:
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.
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
}
Post a Comment