也许我误解了 data
类的 copy
函数是如何工作的,或者可能存在错误,但以下是 copy
函数未按预期工作:
Kotlin :
data class A {
public var x: String? = null
public var y: String? = null
public var z: B = B.ONE
}
enum class B {
ONE
TWO
THREE
}
Java
A a1 = new A()
a1.setX("Hello")
a1.setY("World")
a1.setZ(B.TWO)
A a2 = a1.copy()
// a2.x is null
// a2.y is null
// a2.z is B.ONE
看起来 copy
只是创建了一个 A
的新实例,而不是复制值。如果我将变量放在构造函数中,则会分配值,但这与构造新实例没有什么不同。
最佳答案
好吧,我在文档中漏掉了这句话:
If any of these functions is explicitly defined in the class body or inherited from the base types, it will not be generated.
事实上,这使得 copy
并不比 Java 互操作的构造函数好。
关于java - 从 Java 类调用时,Kotlin 数据类复制函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28620782/