Skip to Content
Author's profile photo Jerry Wang

Regarding Expression in JavaScript and Scala

Consider this example below:


You will get the following output in Console:


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.


Then we get the result below:


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



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.



Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.