I would like to pass a function by name do something before its execution. Consider the following example:
class Runner {
def apply(procedure: => Unit) = {
println("running procedure")
procedure
}
}
new Runner()(println("procedure!")) // #1
new Runner(){println("procedure!")} // #2
The only difference between call #1 and #2 is in curly braces. While the first call outputs
running procedure
procedure!
as expected, in the second call only
procedure!
is printed.
It seems that when curly braces are used, the procedure is not passed by name but executed instead. Why are the curly and round brackets not interchangeable in this example?
First statement:
In first case, when parenthesis are used,
apply()method gets invoked andprintln("procedure!")is passed as argument. So the first statement is equivalent to:Hence the output is:
Second statement:
While in second case you are creating an anonymous class by extending
Runner. So in second case statementprintln("procedure!")is executed as part of constructor butapply()is not invoked hence you see onlyas output.
Custom Control Structure
I suppose you intended to create custom control structure by using second statement (though for compiler, it's an anonymous class). If that is the case, you can use below syntax: