当定义闭包时,Scala如何维护变量的值? [英] How does Scala maintains the values of variable when the closure was defined?

查看:155
本文介绍了当定义闭包时,Scala如何维护变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala是否通过复制或引用维护变量的值?

Does scala maintains the values of variable by copy or reference?

例如,在Ruby中,闭包实际上会延长所需的所有变量的生命周期它不会复制它们,但会保留对它们的引用,并且变量本身将不适合垃圾收集(如果语言有垃圾收集),而闭包是在周围。 [SKORKIN]

For example, in Ruby "the closure will actually extend the lifetime of all the variables that it needs. It will not copy them, but will retain a reference to them and the variables themselves will not be eligible for garbage collection (if the language has garbage collection) while the closure is around". [SKORKIN]

推荐答案

Scala中的Closures不会深度复制对象,它们只会保留对象的引用。此外,闭包不会得到它自己的词汇作用域,而是使用周围的词汇作用域。

Closures in Scala also don't deep copy objects, they'll only keep a reference to the object. Moreover, a closure does not get it's own lexical scope, but instead, it uses the surrounding lexical scope.

class Cell(var x: Int)
var c = new Cell(1)

val f1 = () => c.x /* Create a closure that uses c */

def foo(e: Cell) = () => e.x
  /* foo is a closure generator with its own scope */

val f2 = foo(c)    /* Create another closure that uses c */

val d = c          /* Alias c as d */
c = new Cell(10)   /* Let c point to a new object */
d.x = d.x + 1      /* Increase d.x (i.e., the former c.x) */

println(f1())      /* Prints 10 */
println(f2())      /* Prints 2 */

我不能评论垃圾收集,但我认为JVM的垃圾收集器不会删除一个闭包引用的对象,因为只要闭包仍被引用。

I can't comment on garbage collection, but I assume that the JVM's garbage collector will not remove objects that are referenced by a closure, as long as the closure is still referenced.

这篇关于当定义闭包时,Scala如何维护变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆