This is an excerpt from my much longer blog post, How to Use By-Name Parameters in Scala.
“By-name” parameters — also known as call-by-name parameters — are quite different than by-value parameters. Rob Norris, (aka, “tpolecat”) makes the observation that you can think about the two types of parameters like this:
- A by-value parameter is like receiving a
valfield; its body is evaluated once, when the parameter is bound to the function.
- A by-name parameter is like receiving a
defmethod; its body is evaluated whenever it is used inside the function.
Those statements aren’t 100% accurate, but they are decent analogies to start with. The important part of this analogy is that a by-name parameter is like a def in that nothing happens with that parameter until you reference it inside your method. (More on this shortly.)
Another definition of by-name parameters
A little more accurately, the book Scala Puzzlers says that by-name parameters are “evaluated only when they are referenced inside the function.” The Scala Language Specification adds this:
This (by-name) indicates that the argument is not evaluated at the point of function application, but instead is evaluated at each use within the function.
Other possible names for by-name parameters
When you look at those quotes from the Puzzlers book and the Language Specification, you see that they both say, “a by-name parameter is only evaluated when it’s accessed inside a function.” Given that definition, and tpolecat’s definition up above, I find that the following names are more accurate and meaningful than “by-name”:
- Call on access
- Evaluate on access
- Evaluate on use
- Evaluate when accessed
- Evaluate when referenced
However, because I can’t change the universe, I’ll continue to use the terms “by-name” and “call by-name” in this lesson, but I wanted to share those alternate names, which I think are more meaningful.