Scala Functions Call-by-Name

Advertisements


Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that we don't want evaluated until it's called within our function? For this circumstance, Scala offers call-by-name parameters.

A call-by-name mechanism passes a code block to the callee and each time the callee accesses the parameter, the code block is executed and the value is calculated.

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

   def time() = {
      println("Getting time in nano seconds")
      System.nanoTime
   }
   def delayed( t: => Long ) = {
      println("In delayed method")
      println("Param: " + t)
      t
   }
}

Here, we declared the delayed method, which takes a call-by-name parameter by putting the => symbol between the variable name and the type. When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
In delayed method
Getting time in nano seconds
Param: 81303808765843
Getting time in nano seconds

C:/>

Here, delayed prints a message demonstrating that the method has been entered. Next, delayed prints a message with it's value. Finally, delayed returns t.



Advertisements
Advertisements