A trivial example should help clarify the difference about the two approaches.
Let's consider a useless function that gets as parameters a couple of integers and always returns zero.
def zero(a: Int, b: => Int) = 0Notice that the first parameter is passed to the function by-value, while the second, as specified by the arrow "=>" notation, is passed by-name.
Function zero() looks pretty harmless. However, we could have big troubles if we use it in conjunction with something like this:
def silly() : Int = sillyFunction silly() just resolves in an infinitive loop, that would let our program running forever without giving the user any satisfaction.
If I pass silly() to zero() as its second parameter, I'll have no problem at all:
println(zero(42, silly))Being passed by-name, and not being actually used in zero(), silly() won't be evaluated.
On the contrary, you want to avoid this:
println(zero(silly, 42)) // !!!Here silly() is passed by-value, this means that Scala tries to calculate its value to pass it to zero(), even if it has no use at all for it. And this would let the user waiting forever for its feedback.
No comments:
Post a Comment