1

I'm a beginner in Scala, and I'm confused on how shallow copy works for case class var. I tried an example similar to the answer https://stackoverflow.com/a/52967063/11680744. This is my code.

case class Entity(eType: String, var unique : Boolean)

val entity = Entity("number", true)
val entity2 = entity.copy()
entity2.unique = false

println(entity)
println(entity2)

The Output is:

Entity(number,true)
Entity(number,false)

Why is the change in entity2 not reflected in entity?

Vjay_Rav
  • 25
  • 5
  • 3
    `var` in a **case class** is a bad practice. And if you want mutations to one copy to be reflected on the other copy, you are not only defeating the purpose of such _(copy)_ but that will bring you a lot of headaches in the future. – Luis Miguel Mejía Suárez Jan 28 '20 at 11:54
  • @LuisMiguelMejíaSuárez Thanks. But, I'm aware that it is a bad usage. Tried it just to understand the working of copy(). – Vjay_Rav Jan 29 '20 at 06:04

1 Answers1

1

Your code is equivalent to the one in the linked question (as opposed to the answer), with

 entity2.unique = false

corresponding to

 p1.firstname = "raghu"

In the answer

 a1.l.remove(1)

doesn't reassign a1.l, so a1.l and a2.l remain pointing at the same ArrayBuffer.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • It may be useful to mention that at the end `copy` is not really _copying_ the class. It just calls the constructor to create a new instance and uses the values of the current instance as the defaults of the arguments. – Luis Miguel Mejía Suárez Jan 28 '20 at 11:57
  • @LuisMiguelMejíaSuárez Calling the constructor with the current instance values as default arguments. Isn't it the way an _actual copy_ of an object is generally created? – Vjay_Rav Jan 29 '20 at 06:15
  • @Vjay_Rav not necessary, you may just copy the memory occupied by one object to another object, that way the inner state may be preserved. That is a somewhat common assumption. – Luis Miguel Mejía Suárez Jan 29 '20 at 10:54