Additional Blogs by SAP
Showing results for 
Search instead for 
Did you mean: 
0 Kudos

Can you correctly give the output of these two function call, way1() and way2()?


Check the generated Java code for way1 and way2 and you can find the reason. I use the number to indicate the execution sequence. For way1, the two evaluated statement bundled in Scala code are also bundled and executed together within apply$mcV$sp().

For way2, the difference is that although these following codes are written within the same {} in scala code, however in the generated Java code, the println("way2 being evaluated...")  is executed before way2().

println("way2 being evaluated...")

()=>{println("way2 evaluated finished")} 


For way1, code here is the argument name which represents an expression whose execution result is Unit ( just like void in Java ).

def way1(code: => Unit){
    println("way1 start")
    println("way1 end")

The expressions passed in will simply be executed one by one, as illustrated in the generated Java code. As a result the folluwing call variant also work:

Since the code is actually not a function, so if I add () after it, I will meet with error:

If I change Unit to Int, I will get the error below:

This is because now the expression I use to pass into the way1() should return a value with type Int. The correction could be pretty easy:

Let's go back to way2. code: ()=> Unit means it asks for a variable which is exactly a function, with no argument and return Unit.

If we remove the () in line 24, the function passed in will not be executed.

If we comment out the function, there will be a complaint about argument mismatch, since now only an expression is tried to pass in.

If I pass a function with wrong type deliberately, I could see compile error as expected: