mercredi 1 mars 2017

Are Scala closures as flexible as C++ lambdas?

I know the question seems a bit heretical. Indeed, having much appreciated lambdas in C++11, I was quite thrilled to learn a language which was built to support them from the beginning rather than as a contrived addition.

However, I cannot figure out how to do with Scala all I can do with C++11 lambdas.

Suppose I want to make a function which adds to a number passed as a parameter some value contained in a variable a. In C++, I can do both

int a = 5;
auto lambdaVal = [ a](int par) { return par + a; };
auto lambdaRef = [&a](int par) { return par + a; }; 

Now, if I change a, the second version will change its behavior; but the first will keep adding 5.

In Scala, if I do this

var a = 5
val lambdaOnly = (par:Int) => par + a

I essentially get the lambdaRef model: changing a will immediately change what the function does. (which seems somewhat specious to me given that this time a isn't even mentioned in the declaration of the lambda, only in its code. But let it be)

Am I missing the way to obtain lambdaVal? Or do I have to first copy a to a val to be free to modify it afterwards without side effects?

Aucun commentaire:

Enregistrer un commentaire