The Scala Way — Call-by-value & Call-by-name

Hello guys!

Welcome to my new journey to become a better developer, this time I will dive into Scala.

Why Scala?

It’s been a while since I discovered the amazing world of maths and all those problems that surround the industry: optimizations, statistics, reducing costs, etc…

I also realized that we need lots of data, lots of processing, better heuristics and better data structures.

So I decided to study more about it and take this opportunity to learn something totally new to me, like functional programming.

Why I choose Scala? The first reason is that I can take advantage of the functional programming with OOP, the second reason is that I intend to use Spark in the future and the third reason is that a great developer from Brazil, Ju Gonçalves, told me that Scala would be a great start into the world of functional programming, she also wrote this excelent article.

I’m doing the coursera’s course Functional Programming Principle in Scala and as it goes on I’ll write the most interesting parts. So let’s get started!

Evaluation Strategy

When we call a function in Scala, it will evaluate the expression in this way:

def sum(x: Int, y: Int) = x + y
sum(1 + 1, 2)
sum(2, 2)

So what it is doing?

  1. First it evaluate all function arguments, from left to right;
  2. Then it replaces the function application by the function’s right-hand side, and, at the same time;
  3. Replace the formal parameters of the function by the actual arguments

Also this is known as Call-by-value strategy, it has the advantage that it evaluates every function arguments only once.

Pretty simple, no?

But Scala has another evaluate strategy called Call-by-name, this is one of the reason I decide to wrote about it and I would love to know real worlds scenarios, please tell me if you know about it!

Call-by-name will only evaluate the function argument if it has been used in the body function, otherwise it will no be evaluated.

Look at this function:

def test(x: Int, y: => Int) = x + x
test(7, 2 * 4)

Note the use of => in the expression “y: => Int”, that’s how we define a CBN expression.

If we had used a CBV (call-by-value), it would evaluate the function arguments in this way:

def test(x: Int, y: Int) = x + x
test(7, 2 * 4)
test(7, 8)

In other hands, using a CBN strategy we save some steps, which will result in a more faster evaluation:

def test(x: Int, y: => Int) = x + x
test(7, 2 * 4)

This is because we are not using the y variable in the current function!

When to use call-by-name and call-by-value?

As all of this is new for me, questions like this “When to use call-by-name and call-by-value?” can come in mind, so I’m sharing this link that I found very helpful in the stackoverflow.

That’s all folks, thanks!