Polymorphism for data class copy method


Given a common supertype of my data classes, I’d like to access the data class’s copy method from the supertype.

So given data classes implementing Aging, the following would become possible (without explicitly overriding the copy(Int) method):

interface Aging {
  val age : Int
  fun copy(age: Int)

class RipeningProcess(){
  fun ripen(products : List<Aging>) =
    products.map { it.copy(age = it.age + 1) } 

This works for dataclasses that don’t have any additional properties. Their copy method overrides the one from the interface, but when a dataclass has additional properties, the copy method is not overloaded anymore.

This is a bit puzzling on one hand, since the compiler knows the property exists and is addressable in the copy method. On the other hand, the method is obviously not overridden. And even for the overloading copy method, parameter order is not defined, so it would only work for calls with named arguments.

That last constraint makes it complex, since the definition of copy on Aging (as above) says nothing about a restriction to call it with named arguments only. And there is java interop complexity as well.

Notwithstanding, it would be nice to be able to indicate an interface to be copyable, to perform updates on (immutable) data classes.

I posted a question about this workflow on stackoverflow https://stackoverflow.com/questions/45584242/how-to-update-data-classes-implementing-a-common-interface.

Dreaming further, something like this comes to mind:

data interface Aging {
   val age : Int