Consider this example below:
Image may be NSFW.
Clik here to view.
You will get the following output in Console:
Image may be NSFW.
Clik here to view.
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.
Then we get the result below:
Image may be NSFW.
Clik here to view.
For Scala, it will not have such issue. See code below:
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
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.
Image may be NSFW.
Clik here to view.