Search⌘ K
AI Features

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.

Scala
def evaluate(x: Int, y: Int) ={
x * x
}

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.

Technical Quiz
1.

evaluate(2,3)

A.

CBV

B.

CBN

C.

same


1 / 3

If we wanted the evaluate function to evaluate its first parameter using CBN, the function would be written as below.

Scala
def evaluate(x: => Int, y: Int) ={
x * x
}
// Driver Code
print(evaluate(7, 2*4))

In the next lesson, we will go over which evaluation strategy should be used depending on the expression to be evaluated.