Every computation in Scala is treated like a mathematical function, and the evaluation of these functions is made following the Substitution Model which has many strategies, two of them are:

Call-by-value Strategy

This is the strategy by default, the arguments of the function are evaluated before the function itself, like this example:

def test(x:Int, y:Int) = x+x

test(7,2*4)
test(7,8)
7+7
14
Call-by-name Strategy

In this case, the arguments aren’t evaluated before the function is called, they are evaluated whenever they appear in the function, like this:

def test(x:=>Int, y:=>Int) = x+x

test(7,2*4)
7+7
14

And…what is this for?

Saving time. In the previous examples, the call-by-name strategy is faster because it has fewer evaluations than the call-by-value strategy.

This strategies also apply to values?

Yes, they do.

The def form uses call-by-name strategy and the right part of the assignation is evaluated with each use of the value.

The val form uses call-by-value strategy and the right part of the assignation is evaluated in the definition itself.

For example, if we define this function:

def loop: Boolean = loop

And then we make this assignation:

def x = loop

We cause an infinity loop only if x is used in the rest of the code.

On the other hand, if we make this assignation:

val x = loop

This definition already causes an infinity loop.

goto Part I
goto Part III