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:
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:
The parameter, i
, is evaluated every time you ask for the value...