-->

scala copy objects

2020-08-10 18:57发布

问题:

Is there a way to make a copy of an object (or even better a list of objects)? I'm talking about custom objects of classes that may be extended by other classes.

example:

class Foo() {
   var test = "test"
}

class Bar() extends Foo {
   var dummy = new CustomClass()
}

var b = new Bar()
var bCopy = b.copy() // or something?

回答1:

In Java, they tried to solve this problem a clone method, that works by invoking clone in all super-classes, but this is generally considered broken and best avoided, for reasons you can look up (for example here).

So in Scala, as genereally in Java, you will have to make your own copy method for an arbitrary class, which will allow you to specify things like deep vs shallow copying of fields.

If you make you class a case class, you get a copy method for free. It's actually better than that, because you can update any of the fields at the same time:

case class A(n: Int)
val a = A(1)         // a: A = A(1)
val b = a.copy(a.n)  // b: A = A(1) 
val c = a.copy(2)    // c: A = A(2)

However inheriting from case classes is deprecated.