Why Scala case class copy method parameterised only with the variables defined in the case class?
The question based on on the Q&A:
Case class copy does not maintain state of an inherited trait
Short summary - when trait is defined with a field and extended by a case class, copy on the case class will create the new class instance only with the variables defined in case class, without the extended trait.
trait A {
var list: List[Int] = List()
def add(element: Int) = {
list = element :: list
}
}
case class B(str: String) extends A {
val b = B("foo")
println("B1: " + b.list)
b.add(1)
b.add(2)
b.add(3)
println("B2: " + b.list)
val b2 = b.copy(str = "bar")
println("B3: " + b.list)
println("B4: " + b2.list)
}
Here, B4: () will be empty, while B3:(3,2,1)
copyfor case classes, they simply didn't think about this use case, and didn't preventcopy-codegen, and also didn't emit an error or at least a warning. Maybe you could just submit this as an issue in the scala compiler, so that it at least outputs a warning... - Andrey Tyukin