Maybe I'm misinterpreting how the copy
function of a data
class works or maybe there's a bug, but the following is example of the copy
function not working as expected:
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
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.
Which, infact, makes copy
no better than a constructor for Java interop.
What you can do to get around the limitations of Kotlin's copy(), is to create your own copy function inside your data class. Example below:
data class User(val name : String, val property: String) {
fun copy() : User {
//uses the fields name and property defined in the constructor
return User(name,property)
}
//or if you need a copy with a changed field
fun copy(changedProperty : String) : User {
return User(name, changedProperty)
}
}
For interop with java you can make function that use kotlin generated .copy
@Entity
data class User(@PrimaryKey var id: Int = 0,
var firstName: String? = null,
var lastName: String? = null,
var phone: String? = null,
var email: String? = null,
var phoneCode: String? = null,
var tokenId: String? = null,
var provider: SocialProvider? = null) : Serializable {
var countryCodeIso: String? = null
set(countryCodeIso) {
if (countryCodeIso != null) {
field = countryCodeIso.toLowerCase()
}
}
fun javaCopy(): User {
val user = copy()
user.countryCodeIso = countryCodeIso
return user
}}
来源:https://stackoverflow.com/questions/28620782/kotlin-data-class-copy-function-not-working