Search code examples
scalafunctional-programmingcopycloneimmutability

Does case class' copy-method use Structural Sharing?


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?


Solution

  • 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.