scala copy objects

大城市里の小女人 提交于 2020-01-23 04:44:31

问题


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.



来源:https://stackoverflow.com/questions/8085857/scala-copy-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!