如何在 Scala 中克隆对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6417450/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:07:27  来源:igfitidea点击:

How to clone objects in Scala?

scalaclone

提问by ricardogobbo

Recently had some problems to copy a complex object. Its internal organization is composed of several nested objects. I noticed that the clone()is not available.

最近在复制复杂对象时遇到了一些问题。它的内部组织由几个嵌套的对象组成。我注意到clone()不可用。

What is the best solution to solve the problem?

解决问题的最佳方案是什么?

采纳答案by Daniel C. Sobral

If that complex object is mutable or contain mutable parts, then the solution is the same as in Java. Check Java questions & posts about it and do that.

如果该复杂对象是可变的或包含可变部分,则解决方案与 Java 中的相同。检查 Java 问题和有关它的帖子,然后执行此操作。

If everything is immutable, then you don't need and shouldn't clone anything. At best, you should make a shallow copy of the object, changing only the fields that need changing, and, at worst, you use something like lenses or zippers to copy some deep object and propagate the change upwards. See questions on Scala about lenses and zippers for that.

如果一切都是不可变的,那么您不需要也不应该克隆任何东西。充其量,您应该制作对象的浅层副本,仅更改需要更改的字段,最坏的情况是,您使用镜头或拉链之类的东西复制一些深层对象并将更改向上传播。请参阅有关 Scala 的有关镜头和拉链的问题。

回答by akauppi

I got a sample code that works for cloning mutable-state objects here: Implementing '.clone' in Scala

我在这里得到了一个可用于克隆可变状态对象的示例代码:Implementing '.clone' in Scala