scala copy objects

三世轮回 提交于 2019-12-04 23:26:21

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.

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