Quantcast
Viewing all articles
Browse latest Browse all 2548

Regarding Expression in JavaScript and Scala

Consider this example below:

Image may be NSFW.
Clik here to view.
clipboard1.png

You will get the following output in Console:

Image may be NSFW.
Clik here to view.
clipboard2.png

The two console.log tries to simulate some expensive calculation task. Here although the branch for z has actually no chance to  execute, however the expression is still needed to evaluate before passed into function f.

 

The solution is to simply wrap the calculation into a function, since a function body is evaluated only if the function is called.

Image may be NSFW.
Clik here to view.
clipboard3.png

Then we get the result below:

Image may be NSFW.
Clik here to view.
clipboard4.png

For Scala, it will not have such issue. See code below:


Image may be NSFW.
Clik here to view.
clipboard5.png

Image may be NSFW.
Clik here to view.
clipboard6.png

The reason is for the exp1 :=> Unit in Scala, it means the function exp_test1 will accept a series of expression which produce Unit as return type, and Scala compile will compile the expression into the body code of a new function AbstractFunction0.mcV.sp, thus those expression could only be executed once the wrapper function has chance to be executed.

Image may be NSFW.
Clik here to view.
clipboard7.png

Image may be NSFW.
Clik here to view.
clipboard8.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>