从Java类调用Kotlin数据类复制功能不起作用 [英] Kotlin data class copy function not working when called from java class
问题描述
也许我误解了data
类的copy
函数的工作方式,或者可能是一个错误,但是以下是copy
函数无法正常工作的示例:
Maybe I'm misinterpreting how the copy
function of a data
class works or maybe there's a bug, but the following is an example of the copy
function not working as expected:
科特琳:
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
的新实例,而不是复制值.如果我将变量放入构造函数中,则将分配值,但这与构造新实例没有什么不同.
It seems that copy
is just making a new instance of A
and not copying the values. If I put the variables in the constructor, the values are assigned, but then it's no different than constructing a new instance.
推荐答案
好的,我在文档中错过了这句话:
Okay, I missed this sentence in the docs:
如果这些函数中的任何一个在类主体中显式定义或从基本类型继承,则不会生成.
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互操作的构造函数好.
Which, infact, makes copy
no better than a constructor for Java interop.
这篇关于从Java类调用Kotlin数据类复制功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!