Is it possible to add @JvmOverloads to the generated copy(...) method in Kotlin?

Viewed 442

Suppose I have the following Kotlin class:

data class Person(val firstName: String, val lastName: String)

Because this is a data class, a method with the following signature will be automatically generated:

fun copy(firstName: String = this.firstName, lastName: String = this.lastName): Person

Now, I'd like to call this method from Java code, like:

Person john = new Person("John", "Smith");
Person adam = john.copy("Adam");

I am expecting to have two Person objects now: "John Smith" and "Adam Smith".

Sadly, the copy method does not have overloaded variants and I don't see any way to add them via @JvmOverloads.

So far I've tried to overload it and create an extension, but it is shadowed and works like a static method in Java (plus there's a lot of boilerplate):

@JvmOverloads
fun Person.copy(firstName: String = this.firstName, lastName: String = this.lastName): Person {
    return this.copy(firstName = firstName, lastName = lastName)
}

Is it possible to do in a way that doesn't require too much code to be written?

1 Answers

No. But we can override the copy method by ourselves. Like this:

data class CustomTextInfo(
    val text: String,
    val textColor: Int,
    val backgroundColor: Int,
    val fontId: Int
) {
    fun copy(): CustomTextInfo {
        return CustomTextInfo(text, textColor, backgroundColor, fontId)
    }
}
Related