Scala Call-by-Name Functions (call-by-name)
Scala's interpreter has two ways of evaluating function arguments:
- Call-by-value: first compute the value of the argument expression, then apply it inside the function;
- Call-by-name: pass the unevaluated argument expression directly into the function
With call-by-value, the argument expression is evaluated before entering the function, whereas call-by-name evaluates the argument expression inside the function.
This leads to a phenomenon: every time a call-by-name argument is used, the interpreter evaluates the expression again.
object Test {
def main(args: Array[String]) {
delayed(time());
}
def time() = {
println("获取时间,单位为纳秒")
System.nanoTime
}
def delayed( t: => Long ) = {
println("在 delayed 方法内")
println("参数: " + t)
t
}
}
In the example above we declared a delayed method, which uses the => symbol between the variable name and type to set call-by-name. Running the above code produces the following output:
$ scalac Test.scala
$ scala Test
在 delayed 方法内
获取时间,单位为纳秒
参数: 241550840475831
获取时间,单位为纳秒
In the example, the delay method prints a message indicating it has been entered, then prints the received value, and finally returns t.
Scala Functions