简体   繁体   English

Scala封闭词法作用域

[英]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 在这里f2()打印2,因为scala不会做深层复制,为什么值仍然保持为1,它应该是10。

2) I had read smomehere, Closure in scala dont deep copy the objects, they just keep reference to the object. 2)我读过smomehere,在scala中的Closure并没有深深复制对象,它们只是保持引用对象。 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). 由于复制示例的方式,您的示例有些难以理解(看起来所有代码在创建Cell时都在运行,但如果是这样,您将获得无限递归)。 The reason f1 and f2 return different results is that they are pointing at different Cells. f1和f2返回不同结果的原因是它们指向不同的单元。 You are right that when you write: 你说的对:

val d = c

both c and d contain the same reference. c和d包含相同的引用。 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. c现在是对新单元格的引用,而d将不会复制该引用。

It's easier to see this with REPL, which can print hexadecimal reference locations. 使用REPL可以更轻松地看到它,它可以打印十六进制参考位置。

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. 我们可以看到a和b包含对同一单元格的引用。

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. 当我们更新a所引用的类时,它也会同时更新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). 当我们将变量a分配给新单元格时,它具有不同的引用位置(它是Cell的不同实例)。 b still has the same reference (why wouldn't it?). b仍然有相同的引用(为什么不呢?)。

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

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