Scala function call-by-name


Release date:2023-11-15 Update date:2023-11-15 Editor:admin View counts:142

Label:

Scala function call-by-name

Scala’s interpreter has two ways to parse function parameters (function arguments):

  • call-by-value: first evaluate the value of the parameter expression, and then apply it inside the function

  • Ncall-by-name: applies unevaluated parameter expressions directlyto the inside of a function

Before entering the interior of the function, the value transfer method has already calculated the value of the parameter expression, while the alias call calculates the value of the parameter expression inside the function.

This creates the phenomenon that the interpreter evaluates the value of the expression each time a name call is used.

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

   def time() = {
      println("Obtain time in nanoseconds")
      System.nanoTime
   }
   def delayed( t: => Long ) = {
      println("Within the delayed method")
      println("parameter: " + t)
      t
   }
}

In the above example, we declared delayed method, which is used in variable names and variable types => symbol to set the alias call. Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Within the delayed method
Obtain time in nanoseconds
parameter: 241550840475831
Obtain time in nanoseconds

In the instance delay method prints a message indicating that it entersthe method, and then delay method prints the received value and finally returns t.

Powered by TorCMS (https://github.com/bukun/TorCMS).