这个问题在搜索中的排名很高,对于那些刚接触 kotlin 的人来说可能会感到困惑,因为问题的示例代码不是典型的 kotlin 代码或复制功能的使用。我在下面添加了一些示例代码,以帮助阐明发生了什么,并展示了数据类的典型用法。
简而言之,copy
从 kotlin 类调用该函数时最有用。我同意从 java 代码调用时它的行为并不明显。
//
// A.kt
//
// this is an idiomatic kotlin data class. note the parens around the properties, not braces.
data class A(
val x: String? = null,
val y: String? = null,
val z: B = B.ONE
) {
// this javaCopy function is completely unnecessary when being called from kotlin; it's only here to show a fairly simple way to make kotlin-java interop a little easier (like what Nokuap showed).
fun javaCopy(): A {
return this.copy()
}
}
enum class B {
ONE,
TWO,
THREE
}
fun main() {
val a1 = A("Hello", "World", B.TWO)
// here's what copy usage looks like for idiomatic kotlin code.
val a2 = a1.copy()
assert(a2.x == "Hello")
assert(a2.y == "World")
assert(a2.z == B.TWO)
// more typical is to `copy` the object and modify one or more properties during the copy. e.g.:
val a3 = a1.copy(y = "Friend")
assert(a2.x == "Hello")
assert(a3.y == "Friend")
}
public class App {
public static void main(String[] args) {
A a1 = new A("Hello", "World", B.TWO);
// the kotlin copy function is primarily meant for kotlin <-> kotlin interop
// copy works when called from java, but it requires all the args.
// calling the `javaCopy` function gives the expected behavior.
A a2 = a1.javaCopy();
assert a2.getX().equals("Hello");
assert a2.getY().equals("World");
assert a2.getZ().equals(B.TWO);
}
}
数据类的官方文档,包括copy
函数:
https ://kotlinlang.org/docs/reference/data-classes.html