Quantcast
Channel: SCN : Blog List - All Communities
Viewing all articles
Browse latest Browse all 2548

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

$
0
0


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

clipboard1.png

Answer:

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

clipboard3.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")} 

clipboard4.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:

clipboard5.png

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

clipboard6.png

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

clipboard7.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:

clipboard8.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.

clipboard9.png

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

clipboard10.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.

clipboard11.png

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


clipboard12.png

clipboard13.png

clipboard14.png


Viewing all articles
Browse latest Browse all 2548

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>