Consider this example below:

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

You will get the following output in Console:

/wp-content/uploads/2015/12/clipboard2_845511.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.

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

Then we get the result below:

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

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


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

/wp-content/uploads/2015/12/clipboard6_845515.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.

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

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


To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply