Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
Luka Jacobowitz Avatar asked Mar 01 '16 08:03

Luka Jacobowitz


People also ask

What methods get generated when we declare a case class?

equals and hashCode methods are generated, which let you compare objects and easily use them as keys in maps.

For which kind of data should you use a case class?

Case classes are good for modeling immutable data. In the next step of the tour, we'll see how they are useful in pattern matching.

What is the use of case class in Scala?

The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.

What are case classes in spark?

The case class defines the schema of the table. The names of the arguments to the case class are read using reflection and they become the names of the columns. Case classes can also be nested or contain complex types such as Sequences or Arrays.


1 Answers

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.

like image 183
0__ Avatar answered Oct 09 '22 23:10

0__