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

Regarding Expression in JavaScript and Scala

$
0
0

Consider this example below:

clipboard1.png

You will get the following output in Console:

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.

clipboard3.png

Then we get the result below:

clipboard4.png

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


clipboard5.png

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.

clipboard7.png

clipboard8.png



Viewing all articles
Browse latest Browse all 2548

Trending Articles