Home > Software engineering >  Signature of a generic copy function in an interface for data class?
Signature of a generic copy function in an interface for data class?

Time:01-11

I've an interface for data class containing only one value, like this:

interface Valuable<T> {
    val value: T
}

and for example

data class DataClass(override val value: String) : Valuable<String>

now i would like to add the copy method in the interface, notably to ease a test

however no signature of copy makes the trick.

Adding the following in the interface

fun copy(value: T): Valuable<T>

doesn't compile with:

Function 'copy' generated by the data class has default values for parameters, and conflicts with member of supertype 'Valuable'

Changing the method to

fun copy(value: T = value): Valuable<T>

is right i think but doesn't compile with:

Parameter 'value' is uninitialized here

Why am i missing?

CodePudding user response:

copy is a reserved word

Are you trying to run the special copy function to clone the instance?

  1. If not, then pick any other method name and you will be fine
  2. If you are, then the problem why this is disallowed (I presume) is that the special copy operation needs to know what concrete object to create for you. Whenever I have had several subclasses (or concrete implementations of an interface) you end up writing code several times to execute the "common" code several times in different code branches for each subclass.

CodePudding user response:

Data class in Kotlin has a copy method built into it already. Data Class Copy

This function cannot be overridden, but a new copy method can be defined.

If you are not required to use a data class, just switching to a normal class will remove any copy method restrictions.

When trying to use an interface to define a new copy:

Function 'copy' generated for the data class has default values for parameters, and conflicts with member of supertype 'Valuable'

In order to define your own copy, either in the data class or the interface, you can define it with 0 arguments. For your example:

fun copy(): Valuable<T>
  • Related