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
?
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