案例类别的复制方法是否使用结构共享? [英] Does case class' copy-method use Structural Sharing?
问题描述
Scala中的结构共享不可变集合非常简单,并且有大量的材料可以理解它。
现在每个Scala case class 自动定义一个
copy
方法,它返回一个新的属性指定的新属性,我的问题是,该方法使用结构共享?
所以,当我有一个
case class A(x: HugeObject,y:Int)
并调用 copy
method
val a = A(x,y)
val b = a.copy(y = 5 )
是否复制x?
一个case类是扁平元组,因此当使用 copy
时,为每个产品元素分配一个新实例。但是,元素本身并不是以任何形式被复制,而是被引用共享(除了传入 copy
方法)的值。
case class Foo(a:AnyRef,b:AnyRef)
val f1 = Foo(new AnyRef,new AnyRef)
val f2 = f1.copy(a = new AnyRef)
f1.a == f2.a // false
f1.b == f2.b // true
f1.b eq f2 .b // true
所以在你的情况下, x
仅作为相同的引用重用,但不会在结构上重复。
Structural Sharing in Scala Immutable Collections is quite straightforward and there's a lot of material floating around to understand it.
Now every Scala case class
automatically defines a copy
method, which returns a new copy with the new attributes specified, my question is, does the method use Structural Sharing?
So when I have a
case class A(x: HugeObject, y: Int)
and call the copy
method
val a = A(x,y)
val b = a.copy(y = 5)
Does it copy x?
A case class is flat tuple, as such when using copy
a new instance is allocated with slots for each product element. However, the elements themselves are not in any form duplicated but shared by reference (except for the value passed into the copy
method).
case class Foo(a: AnyRef, b: AnyRef)
val f1 = Foo(new AnyRef, new AnyRef)
val f2 = f1.copy(a = new AnyRef)
f1.a == f2.a // false
f1.b == f2.b // true
f1.b eq f2.b // true
So in your case, x
is only reused as the same reference but not structurally duplicated.
这篇关于案例类别的复制方法是否使用结构共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!