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?
Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.
A case class has all of the functionality of a regular class, and more. When the compiler sees the case keyword in front of a class , it generates code for you, with the following benefits: Case class constructor parameters are public val fields by default, so accessor methods are generated for each parameter.
A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With