Quiz: CBV or CBN?
Learn to differentiate between call-by-value and call-by-name evaluation in Scala functions. Discover how these strategies impact the speed and efficiency of function execution, and understand when to apply each approach to optimize your Scala code.
We'll cover the following...
While Scala’s default evaluation strategy is call-by-value, call-by-name can be enforced using =>. Hence, it is important to know when to use CBV and when to use CBN. Take a look at the function below.
This function is just like our square function with an added extra parameter y. Now, y isn’t required for the evaluation of the function’s body. Can you figure out which evaluation strategy is faster in the following function calls to the evaluate function?
By faster, we simply mean taking a lesser number of steps to reach the final result.
evaluate(2,3)
CBV
CBN
same
If we wanted the evaluate function to evaluate its first parameter using CBN, the function would be written as below.
In the next lesson, we will go over which evaluation strategy should be used depending on the expression to be evaluated.