Easy Tutorial
❮ Recursion Functions Scala Iterators ❯

Scala Call-by-Name Function Calls

Scala Functions

The Scala interpreter has two ways of parsing function arguments:

Before entering the function, the call-by-value method has already calculated the value of the argument expression, while call-by-name calculates the value of the argument expression within the function.

This results in a phenomenon where every time a call-by-name is used, the interpreter calculates the value of the expression once.

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

   def time() = {
      println("Getting time in nanoseconds")
      System.nanoTime
   }
   def delayed( t: => Long ) = {
      println("Inside the delayed method")
      println("Argument: " + t)
      t
   }
}

In the above example, we declare the delayed method, which uses the => symbol for variable names and types to set up a call-by-name. Running the above code produces the following output:

$ scalac Test.scala 
$ scala Test
Inside the delayed method
Getting time in nanoseconds
Argument: 241550840475831
Getting time in nanoseconds

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

Scala Functions

❮ Recursion Functions Scala Iterators ❯