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}") ...
Get Scala Functional Programming Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.