One of the first cool features of the Scala language that struck me is the ability to defer the evaluation of a function argument simply by changing the type of the function definition.
In essence, you simply take an existing type declaration for a function argument of a given type:
def succ(x: Int): Int = 1+x
and insert => to defer the evaluation of the expression:
def succ(x: => Int): Int = 1+x
Now, evaluation of the expression passed to succ is deferred and each reference to x in the body of the function succ actually evaluates the given expression.
Kent Tong recently gave a good practical example of how this can be used to defer the computation of debug expressions. This addresses a common problem where computing debug strings too eagerly can slow down a whole application significantly even if the debug strings are never logged!
0 comments:
Post a Comment