Call by Value and Call by Name

Reading Time: 2 minutes

Call by value

In the Call by value method of parameter passing in Scala – a copy is to be passing by the method. This means that the parameters passed to the method have nothing to do with the actual values. These parameters are formal parameters. 

The changes that we make in the formal parameters are not visible in the actual parameters (the values pass while calling the method ).

def adder(x: int)=x+x

Example:-

Callbyvalue

Output:

value

Call by Name

Call-by-name evaluation is similar to call-by-value, but its advantage is that a function argument will not evaluate until we use the corresponding value inside the function body.

Both strategies are reduce to the final value as long as:

  • The reduced expression consists of pure functions
  • Both evaluations terminate

def adder(x: => int)=x+x

Example:-

Callbyname

Output:-

name

We have defined two functions showtime_Callbyvalue and showtime_Callbyname

These functions take the System time in Long type and print it two times.

So now we call both functions bypassing the argument System.nanotime that gives current system time in nano-seconds.

showtime_Callbyvalue(System.nanotime())

showtime_Callbyname(System.nanotime())

Call By-Value or Call By-Name

It is more efficient than call-by-name because it avoids the repeated re-computation of argument expressions that call-by-name entails.

Additionally, it can avoid other side effects because we know when the expressions will be evaluated.

Why not swapping function:-

The most common example demonstrating the use of call by value and call by name is the swapping function.

In Scala, the parameters of the functions are val.

Immutable which means you can’t reinitialize them in the function. This leaves us in a scenario where the easiest way to learn the difference is not applicable.

So, the classical program is created to just give you differences. Now, consider this code, which tries to reinitialize the parameters of Scala.

Example:-

object MyClass {
    def add(a: => Int){
         a = x + 1
        println("sum = "+a)
    };
    def main(args: Array[String]) {
        var a = 34
        add(a)
    }
}

output:-

error: reassignment to val
         a = x + 1
one error found

Conclusion:-

Its function arguments are evaluated once before entering the function, but the call-by-name function arguments are evaluated inside the function only when they are needed.

Reference:-

https://www.geeksforgeeks.org/scala-functions-call-by-name/

Written by 

Shubham is a tech lover who is starting his career with Scala Ecosystem. He is curious about learning. He is known as a good team player.....

2 thoughts on “Call by Value and Call by Name3 min read

Comments are closed.