Scala Call by Value vs. Name

From today, I start working on series of articles about how Scala is special and powerful than regular programming languages, such as Java, under tag scalatips. If you have any confused topic, please feel free to contact me so that I can try to use simple terms and explanations to help you understand it.

Usually, there are a couple of ways when calling functions, such as call-by-reference, call-by-value and call-by-name.

  1. call-by-reference: we are passing an alias of the variable to a function
  2. call-by-value: we are passing the value of formula/variable to a function.
  3. call-by-name: we are passing the whole formula to a function (there is no such saying when the argument is variable).

Note: For C, C++, they support 1. and 2. For Java, it only supports 2. For Scala, it supports 2, and 3.

Below is an example to demonstrate the difference in Scala.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Create a printer utility for demo. 
def printer() = {
println("calling printer")
1 // return value
}

//This is a call-by-value syntax like regular function
def callByValue(x: Int) = {
println("x1=" + x)
println("x2=" + x)
}

//This is a call-by-name syntax by using =>
def callByName(x: => Int) = {
println("x1=" + x)
println("x2=" + x)
}

Then, let’s try the difference by calling them one by one. The result is as follows.

1
2
3
4
scala> callByValue(printer())
calling printer
x1=1
x2=1

For above example, the function firstly evaluate the printer() function. As a result, it prints “calling printer” and value 1. Then, the value 1 is assigned to the argument for function callByValue. Then, the callByValue function prints the x twice for x1 and x2.

1
2
3
4
5
scala> callByName(printer())
calling printer
x1=1
calling printer
x2=1

For above example, the function printer will pass into x as whole twice since the x is being called by callByName twice. As a result, the “calling printer” are shown twice.