English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Scala's interpreter has two ways to parse function parameters (function arguments):
Value call (call-by-value): First calculate the value of the parameter expression and then apply it to the function inside;
Named call (call-by-name): Apply the uncalculated parameter expression directly to the function inside
Before entering the function, the value call method has already calculated the value of the parameter expression, while the named call calculates the value of the parameter expression inside the function.
This causes a phenomenon that the interpreter calculates the value of the expression each time a named parameter call is used.
object Test { def main(args: Array[String]) { delayed(time()); } def time() = { println("Get time, unit in nanoseconds") System.nanoTime } def delayed(t: => Long) = { println("Inside the delayed method") println("Parameters: " + t) t } }
In the above example, we declared the delayed method This method sets the named parameter by using the => symbol. After executing the above code, the output is as follows:
$ scalac Test.scala $ scala Test Inside the delayed method Get time, unit in nanoseconds Parameters: 241550840475831 Get time, unit in nanoseconds
In the example, the delay method prints a message indicating that the method has been entered, followed by the delay method printing the received value, and finally returning t.