Given the following code:
object Quizful {
  def main(args: Array[String]) {
    println(s"Delayed time: ${delayed(time())}")
  }

  def time() = {
    println("Getting time in nano seconds")
    System.nanoTime
  }
  def delayed( t: => Long ) = {
    println("In delayed method")
    println("Param: " + t)
    t
  }
}
What will be printed into the console after running this programm?
Explanation
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.
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 Quizful.scala
C:/>scala Quizful
In delayed method
Getting time in nano seconds
Param: 3026149960356229
Getting time in nano seconds
Delayed time: 3026149960537279

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.
Read more: Scala Functions Call-by-Name

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes