Basically there's no technical difference between lazy evaluated parameter and Function0
parameter. There are pro's and cons of both the implementation.
Function0
parameter is definitely verbose. So if you change them to lazy parameter, code will become much readable.
Here is a bug prone situation of lazy evaluation.
Consider following code
def inner = println("inner called")
def execute(f: => Unit) = {
println("executing")
f
}
def redirect(f: => Unit) = {
println("redirecting")
execute(f)
}
redirect(inner) // will print -
// redirecting
// executing
// inner called
Now think for some reason you forget to put =>
in the execute function. Code will compile correctly, but the behavior will be different and might introduce bugs.
def execute(f: Unit) = {
println("executing")
f
}
def redirect(f: => Unit) = {
println("redirecting")
execute(f)
}
redirect(inner) // will print -
// redirecting
// inner called
// executing
But if you use Function0
, the code will not compile. So, the Function0
parameters are less bug prone.
def inner() = println("inner called")
def execute(f:() => Unit) = {
println("executing")
f()
}
def redirect(f:() => Unit) = {
println("redirecting")
execute(f)
}
redirect(inner) // will print -
// redirecting
// executing
// inner called
=========================================
def inner() = println("inner called")
def execute(f:Unit) = {
println("executing")
f
}
def redirect(f:() => Unit) = {
println("redirecting")
execute(f) // Will not compile.
}
Furthermore, You can clearly see when that value is evaluated.
Anyway if you are so sure what you do, you can use any one of them. Decision is yous.