简体   繁体   English

在Scala的闭包内部修改自由变量

[英]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 fa proper, state-of-the-art closure (is it at all a closure)? 是否是适当的,最新的关闭方式(完全是关闭方式)?

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. 现在您可以将函数f传递到某个地方,当您调用它时, a将被更新。 So f is a proper closure. 所以f是一个适当的闭包。 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 . 你的情况,你可以改变a值,或者通过f或直接重新分配a So it isn't clear how do you want to update a and which way is preferable. 因此,尚不清楚您要如何更新a以及哪种方法更可取。

There are several ways to work with closures. 有几种使用闭包的方法。 You can use them to keep some state inside closure (see Lisp cons or list implementation). 您可以使用它们在闭包内部保留一些状态(请参阅Lisp 缺点列表实现)。 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 . 实际上,您的f看起来更像回调,因为它内部没有保留任何状态,但是引用a So even if a is private you can pass f somewhere to be able to update a . 因此,即使a是私有的,您也可以在某个地方传递f来更新a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM