Scala Call-by-Name Function Calls
The Scala interpreter has two ways of parsing function arguments:
Call-by-value: The value of the argument expression is calculated first, then applied within the function;
Call-by-name: The uncalculated argument expression is directly applied within the function.
Before entering the function, the call-by-value method has already calculated the value of the argument expression, while call-by-name calculates the value of the argument expression within the function.
This results in a phenomenon where every time a call-by-name is used, the interpreter calculates the value of the expression once.
object Test {
def main(args: Array[String]) {
delayed(time());
}
def time() = {
println("Getting time in nanoseconds")
System.nanoTime
}
def delayed( t: => Long ) = {
println("Inside the delayed method")
println("Argument: " + t)
t
}
}
In the above example, we declare the delayed method, which uses the => symbol for variable names and types to set up a call-by-name. Running the above code produces the following output:
$ scalac Test.scala
$ scala Test
Inside the delayed method
Getting time in nanoseconds
Argument: 241550840475831
Getting time in nanoseconds
In the example, the delay method prints a message indicating that it has entered the method, then prints the received value, and finally returns t.