Call by name
Typically, parameters are passed by value are by-value that is the value of the parameter is determined before it gets passed to the function. In the REPL session here, we have two functions, g
and f
.
We pass the value of calling getValue()
to f
and g
:
scala> var k = 0 k: Int = 0 scala> def getVal() = { | k += 1 | k | } getVal: ()Int scala> def g(i: Int) = { | println(s"${i}") | println(s"${i}") | println(s"${i}") | } g: (i: Int)Unit scala> g(getVal()) 1 1 1
Refer to the following figure:
![](https://static.packt-cdn.com/products/9781783985845/graphics/B02951_04_06.jpg)
Figure 4.6: Call By Value
The three println
statements in g()
print the same value, 1
:
scala> def f(i: => Int) = { | println(s"${i}") | println(s"${i}") | println(s"${i}") | } f: (i: => Int)Unit scala> k = 0 k: Int = 0 scala> f(getVal()) 1 2 3
Refer to the following figure:
![](https://static.packt-cdn.com/products/9781783985845/graphics/B02951_04_07.jpg)
Figure 4.7: Call by name
The parameter, i
, is evaluated every time you ask for the value...