How does Scala maintains the values of variable when the closure was defined?
closures, scala
Solution
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 */
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.
Problem
Does scala maintains the values of variable by copy or reference? 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]