Thursday 14 December 2017

Scala Call by Value Vs Call by Name






Call by value - evaluates the function arguments before calling the function
Call by name - evaluates the function first, and then evaluates the arguments if need be

Scala uses call-by-value by default, but it switches to call-by-name evaluation if the
parameter type is preceded by =>.

Example:
Infinite loop function:
scala> def loop: Int = loop
loop: Int

function which return x parameter.(It does not required parameter y for evaluation)

scala> def getX(x: Int, y: Int) = x
getX: (Int,Int)Int

scala > getX(1,loop)
.....

It will go into Infinite loop as call by value evaluates parameter y which causes Infinite loop.

Let's make changes in function to make parameter y as call by name.

scala> def getX(x: Int, y: => Int) = x
getX: (Int,Int)Int

scala> getX(1,loop)
res0: Int = 1

Now Instead of Infinite loop we got result as 1 beacuse call by name evaluates argument/parameter if needed.

Call-by-value has the advantage that it avoids repeated evaluation of arguments.
Call-by-name has the advantage that it avoids evaluation of arguments when the
parameter is not used at all by the function

No comments:

Post a Comment