The program looks like this ...
object Delay{
def main(args: Array[String]){
delayed(time())
}
def time()={
println(\"Getting time
The reason why you see this execution order, is because t
is a by-name parameter in your code:
def delayed(t: => Long)
If you defined your delayed
method with a by-value parameter like so:
def delayed(t: Long)
the time()
function would have been evaluated before the call to delayed
, and you would get the following output instead:
Getting time in nanoseconds :
In delayed Method
Param : 139735036142049
The trick is that by-name parameters are called only when they're used, and every time they're used. From the Scala docs:
By-name parameters are only evaluated when used. They are in contrast to by-value parameters.
By-name parameters have the advantage that they are not evaluated if they aren’t used in the function body. On the other hand, by-value parameters have the advantage that they are evaluated only once.