如何在Kotlin中克隆对象?
问题就这么简单.
Kotlin文档仅在访问Java和枚举类中描述克隆.在后一种情况下,克隆只是引发异常.
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?
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.