简体   繁体   中英

Scala closure 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 */

 // f2 wont do any reference/deep copy
  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) */

  // now c.x refers to 10
  println(f1()) /* Prints 10 */
  println(f2()) /* Prints 2 */

Here the f2() prints 2 , As scala wont do deep copy, why the value is still persisted as 1, it should be 10.. where i am going wrong

2) I had read smomehere, Closure in scala dont deep copy the objects, they just keep reference to the object. what do it exactly mean

Your example is somewhat tough to understand due to the way you copied it in (it looks like all the code is run when a Cell is created, but you'd get infinite recursion if that were true). The reason f1 and f2 return different results is that they are pointing at different Cells. You are right that when you write:

val d = c

both c and d contain the same reference. But when you write:

c = new Cell(10)

c is now a reference to a new cell, and d won't copy over that reference.

It's easier to see this with REPL, which can print hexadecimal reference locations.

scala> class Cell(var x: Int)
defined class Cell

scala> var a = new Cell(5)
a: Cell = Cell@368239c8

scala> val b = a
b: Cell = Cell@368239c8

We can see that a and b contain references to the same cell.

scala> a.x = 10
a.x: Int = 10

scala> b.x
res0: Int = 10

When we update the class referenced by a, it also updates for b.

scala> a = new Cell(7)
a: Cell = Cell@5b87ed94

scala> b
res1: Cell = Cell@368239c8

scala> a.x
res2: Int = 7

scala> b.x
res3: Int = 10

When we assign our variable a to a new cell, it has a different reference location (it is a different instance of Cell). b still has the same reference (why wouldn't it?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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