Here's a simple Scala call-by-name example. I ' ll show the normal approach to writing a method and passing in a parameter, and then show a call-by-name (pass by name) Example. 1) A "Normal" Scala method
Here I show how to pass a parameter to a method "normally", i.e., call by value:
Object Test extends App {
def time (): Long = {
println ("In Time ()")
System.nanotime
}
def exec (T:lon g): Long = {
println ("entered exec, calling t ...")
println ("t =" + t)
println ("Calling T again ...")
t
}
println (EXEC (Time ()))
}
The output looks like this:
In time ()
entered exec, calling T
... t = 1363909521286596000
calling T again
... 1363909521286596000
As expected, the values for T is the same. This is because the value of T was determined when this line is invoked:
println (EXEC (Time ()))
2) A call by name example
Next, make the method parameter a call by name parameter:
Object Test extends App {
def time () = {
println ("Entered time () ...")
system.nanotime
}
//uses a by- Name parameter here
def exec (t: = = Long) = {
println ("entered exec, calling t ...")
println ("t =" + t)
println ("Calling T again ...")
t
}
println (EXEC (Time ()))
}
This time, the output is different:
Entered exec, calling T
... Entered time ()
... t = 1363909593759120000
calling T again
... Entered time ()
... 1363909593759480000
The both T invocations yield different results. As stated in the Scala language specification, this is because:
"This indicates the argument are not evaluated at the point of function application, but instead are evaluated at each Use within the function. That's, the argument is evaluated Usingcall-by-name. "
That's a simple call by the name example in Scala.