Scala Function Call-by-Name (call-by-name)

Scala 函数Scala Functions

Scala's interpreter has two ways of parsing function arguments:

  • Call-by-value: first evaluate the value of the parameter expression, then apply it inside the function;
  • Call-by-name: directly apply the unevaluated parameter expression inside the function

Before entering the function, the call-by-value approach has already finished evaluating the parameter expression, while call-by-name evaluates the parameter expression inside the function.

This causes a phenomenon: every time call-by-name is used, the interpreter evaluates the expression once.

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 above example, we declared the delayed method, which uses the => symbol between the variable name and variable type to set up call-by-name. Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
在 delayed 方法内
获取时间,单位为纳秒
参数: 241550840475831
获取时间,单位为纳秒

In the example, the delay method prints a message indicating that it has entered the method, then the delay method prints the received value, and finally returns t.

Scala 函数Scala Functions

Other Extensions