Latest web development tutorials

Scala function call by name

Scala function Scala function

Scala interpreter in two ways analytic function parameters (function arguments) when:

  • For a call (call-by-value): value of the parameter expression is first calculated and then applied to the internal functions;
  • By name call (call-by-name): The parameter expression is not directly applied to the calculation of internal functions

Before entering inside the function is called by value has been calculated on the value of the parameter expression, and call by name argument expression is a value calculated within the function.

This causes a phenomenon, calling each by name when the interpreter will be calculated once the value of the expression to use.

object Test {
   def main(args: Array[String]) {
        delayed(time());
   }

   def time() = {
      println("获取时间,单位为纳秒")
      System.nanoTime
   }
   def delayed( t: => Long ) = {
      println("在 delayed 方法内")
      println("参数: " + t)
      t
   }
}

Examples of the above, we declare a delayed method called by name to set the variable name and type using the => symbol. Implementation of the above code, the output results are as follows:

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

Examples of the method to print a delay information indicating the method, printing method and then delay the received value, and finally return to t.

Scala function Scala function