1
votes

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?

1
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
@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

1 Answers

1
votes

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.