lazy
#
It is natural to expect that arguments are evaluated before entering the functions that use the arguments. For example, the function add()
below is called with the return values of two other functions:
result = add(anAmount(), anotherAmount());
In order for add()
to be called, first anAmount()
and anotherAmount()
must be called. Otherwise, the values that add()
needs would not be available.
Evaluating arguments before calling a function is called eager evaluation.
However, depending on certain conditions, some parameters may not get a chance to be used in the function at all. In such cases, evaluating the arguments eagerly would be wasteful.
A classic example of this situation is a logging function that outputs a message only if the importance of the message is above a certain configuration setting:
enum Level { low, medium, high }
void log(Level level, string message) {
if (level >= interestedLevel) {
writeln(message);
}
}
For example, if the user is interested only in the messages that are Level.high
, a message with Level.medium
would not be printed. However, the argument would still be evaluated before calling the function. For example, the entire format()
expression below, including the getConnectionState()
call that it makes, would be wasted if the message is never printed:
if (failedToConnect) {
log(Level.medium, format("Failure. The connection state is '%s'.", getConnectionState()));
}
The lazy
keyword specifies that an expression that is passed as a parameter will be evaluated only if and when needed:
void log(Level level, lazy string message) {
// ... the body of the function is the same as before ...
}
This time, the expression would be evaluated only if the message parameter is used.
One thing to be careful about is that a lazy
parameter is evaluated every time that parameter is used in the function.
For example, because the lazy
parameter of the following function is used three times in the function, the expression that provides its value is evaluated three times:
Get hands-on with 1400+ tech skills courses.