Saturday, 2 August 2014

Scala Note 1: Call-by-value v.s. Call-by-name

Function parameters can be passed by value or name.
Scala uses call-by-value by default, but it switches to call-by-name evaluation if the
parameter type is preceded by =>.

Call-by-value has the advantage that it avoids repeated evaluation of arguments.
scala> def constOne(x: Int, y: Int) = 1

Call-by-name has the advantage that it avoids evaluation of arguments when the
parameter is not used at all by the function.
scala> def constOne(x: Int, y: => Int) = 1


Call-by-value is usually more efficient
than call-by-name, but a call-by-value evaluationmight loop where a call-by-name

evaluation would terminate.

Consider scala> constOne(1, loop)
Call by name will return 1, while call by value will not terminate.


No comments:

Post a Comment