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 javascri
Scala has lazy val
s, whose initializers are not evaluated unless and until the val is used. Lazy vals may be used as method local variables.
Scala also has by-name method parameters, whose actual parameter expressions are wrapped in a thunk and that thunk is evaluated every time the formal parameter is referenced in the method body.
Together these can be used to achieve lazy evaluation semantics such as are the default in Haskell (at least in my very limited understanding of Haskell).
def meth(i: => Int): Something = {
// ^^^^^^ by-name parameter syntax
lazy val ii = i
// Rest of method uses ii, not i
}
In this method, the expression used as the actual parameter will be evaluated either zero times (if the dynamic execution path of the method body never uses ii
) or once (if it uses ii
one or more times).