Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala copy objects

Tags:

object

copy

scala

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?
like image 735
user485659 Avatar asked Nov 10 '11 20:11

user485659


People also ask

How do you make a copy of an object in Java?

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.

What is a case class?

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.

What is the difference between class and case class in Scala?

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).


1 Answers

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.

like image 116
Luigi Plinge Avatar answered Oct 14 '22 17:10

Luigi Plinge