scala复制对象 [英] scala copy objects

查看:2243
本文介绍了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.

例如:

class Foo() {
   var test = "test"
}

class Bar() extends Foo {
   var dummy = new CustomClass()
}

var b = new Bar()
var bCopy = b.copy() // or something?


推荐答案

code> clone 方法,通过在所有超类中调用 clone 来工作,但这通常被认为是破坏的,您可以查找的原因(例如此处)。

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

所以在Scala中,作为基本上在Java中,你将必须为一个任意类创建自己的复制方法,这将允许你指定像深对浅复制字段。

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.

如果你让你打一个案例类,你会得到一个 c $ c>方法。它实际上比那更好,因为你可以同时更新任何字段:

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)

case类已弃用。

这篇关于scala复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆