iku
iku

Reputation: 1057

Modifying free variable inside a closure in Scala

I wonder whether it makes sense to modify a free variable inside a closure. I can't find anywhere information whether it can be treated as a bad or good practice.

Simple example:

var a = 2;
val f = (x: Int) => {a = x + 2;}
f(2)

Is f a proper, state-of-the-art closure (is it at all a closure)?

Upvotes: 1

Views: 449

Answers (1)

ka4eli
ka4eli

Reputation: 5424

The main purpose of closures is to close over some state and be able to update it. Now you can pass function f somewhere and when you call it, a will be updated. So f is a proper closure. Is it a state-of-the-art? It depends on context and the role of this closure. In your case you can change a value either via f or directly reassigning a. So it isn't clear how do you want to update a and which way is preferable.

There are several ways to work with closures. You can use them to keep some state inside closure (see Lisp cons or list implementation). This way state is declared inside function and nothing can change it from outside. You just return another function - closure which is the only who has access to inner state.

Another example is callbacks. Actually your f looks more like callback since it doesn't keep any state inside it but has a reference to a. So even if a is private you can pass f somewhere to be able to update a.

Upvotes: 2

Related Questions