假设我有以下Kotlin类:
data class Person(val firstName: String, val lastName: String)
因为这是data
类,所以将自动生成具有以下签名的方法:
fun copy(firstName: String = this.firstName, lastName: String = this.lastName): Person
现在,我想从Java代码中调用此方法,如:
Person john = new Person("John", "Smith");
Person adam = john.copy("Adam");
我现在期待有两个Person
物品:“John Smith”和“Adam Smith”。
遗憾的是,copy
方法没有重载变体,我没有看到任何方法通过@JvmOverloads
添加它们。
到目前为止,我已经尝试重载它并创建一个扩展,但它被遮蔽并且像Java中的静态方法一样工作(加上有很多样板):
@JvmOverloads
fun Person.copy(firstName: String = this.firstName, lastName: String = this.lastName): Person {
return this.copy(firstName = firstName, lastName = lastName)
}
是否有可能以不需要编写太多代码的方式进行?
不,但我们可以自己覆盖复制方法。像这样:
data class CustomTextInfo(
val text: String,
val textColor: Int,
val backgroundColor: Int,
val fontId: Int
) {
fun copy(): CustomTextInfo {
return CustomTextInfo(text, textColor, backgroundColor, fontId)
}
}