如何在 Kotlin 中克隆对象? [英] How to clone object in Kotlin?

查看:86
本文介绍了如何在 Kotlin 中克隆对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 文档 仅在访问 Java 和枚举中描述了克隆班级.在后一种情况下, clone 只是抛出一个异常.

The Kotlin documentation describes cloning only in accessing Java and in enum class. In latter case clone is just throwing an exception.

那么,我/应该如何克隆任意 Kotlin 对象?

So, how would I / should I clone arbitrary Kotlin object?

我应该像在 Java 中一样使用 clone() 吗?

Should I just use clone() as in Java?

推荐答案

对于数据类,您可以使用编译器生成的copy() 方法.请注意,它将执行浅拷贝.

For a data class, you can use the compiler-generated copy() method. Note that it will perform a shallow copy.

要创建集合的副本,请使用 toList()toSet() 方法,具体取决于您需要的集合类型.这些方法总是创建一个集合的新副本;它们还执行浅拷贝.

To create a copy of a collection, use the toList() or toSet() methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow copy.

对于其他类,没有 Kotlin 特定的克隆解决方案.如果它符合您的要求,您可以使用 .clone(),如果不符合,您可以构建不同的解决方案.

For other classes, there is no Kotlin-specific cloning solution. You can use .clone() if it suits your requirements, or build a different solution if it doesn't.

这篇关于如何在 Kotlin 中克隆对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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