Scala 复制对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8085857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scala copy objects
提问by user485659
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?
回答by Luigi Plinge
In Java, they tried to solve this problem a clonemethod, that works by invoking clonein all super-classes, but this is generally considered broken and best avoided, for reasons you can look up (for example here).
在 Java 中,他们尝试使用一种clone方法来解决这个问题,该方法通过调用clone所有超类来工作,但这通常被认为是坏掉的,最好避免,原因你可以查一下(例如这里)。
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.
因此,在 Scala 中,就像在 Java 中一样,您必须为任意类创建自己的复制方法,这将允许您指定诸如字段的深拷贝和浅拷贝之类的内容。
If you make you class a case class, you get a copymethod for free. It's actually better than that, because you can update any of the fields at the same time:
如果你让你类 a case class,你会copy免费获得一个方法。它实际上比这更好,因为您可以同时更新任何字段:
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.
但是,不推荐从案例类继承。

