Skip to Content
Author's profile photo Jerry Wang

difference between :=> and :()=> in Scala

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

/wp-content/uploads/2015/12/clipboard1_845519.png

Answer:

/wp-content/uploads/2015/12/clipboard2_845520.png

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().

/wp-content/uploads/2015/12/clipboard3_845521.png

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”)} 

/wp-content/uploads/2015/12/clipboard4_845522.png

Conclusion

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")
    code
    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:

/wp-content/uploads/2015/12/clipboard5_845523.png

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

/wp-content/uploads/2015/12/clipboard6_845524.png

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

/wp-content/uploads/2015/12/clipboard7_845525.png

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:

/wp-content/uploads/2015/12/clipboard8_845526.png

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.

/wp-content/uploads/2015/12/clipboard9_845527.png

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

/wp-content/uploads/2015/12/clipboard10_845528.png

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

/wp-content/uploads/2015/12/clipboard11_845529.png

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


/wp-content/uploads/2015/12/clipboard12_845530.png

/wp-content/uploads/2015/12/clipboard13_845531.png

/wp-content/uploads/2015/12/clipboard14_845532.png

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.