I'm sure this must have been asked before :slightl...
# getting-started
d
I'm sure this must have been asked before 🙂 How to utilize data class
copy
in functions which handle polymorphic data classes, i.e. the functions accept an interface as a parameter? Obviously, since the parameter is an interface there's no
copy
method available. But my intention is for the concrete implementations of that interface to always be data classes. Is there any way how to use
copy
in this situation?
I should add that in the function I want to manipulate only the common (i.e. interface) properties.
It seems that I need
data interface
.
c
data interface
can never be a thing: by nature, something that is purely data cannot be overriden, and by nature, two interface implementations must be different, so they are different data.
However, #arrow may help you with their Optics library (be aware, it requires some code generation)
In general, an interface is contract of behavior and a data class is a contract of state, they are different concepts
🔥 1
thank you color 1
💯 1
m
What I've done is just create a copy function in the interface and have the subclasses implement it by delegating to their copy function.
👍 1
c
Yeah, that works
d
In general, an interface is contract of behavior and a data class is a contract of state, they are different concepts
Well, and couldn't be the "data-ness" also considered as kind of behaviour? Because
copy
actually IS behaviour and the only thing I want from the hypothetical interface is to tell the compiler that the implementations are data classes with the copy method. I guess this will probably quickly hit some limitations in the data class design/technical implementation.
What I've done is just create a copy function in the interface and have the subclasses implement it by delegating to their copy function.
That will work but must be quite verbose, though, no?
c
But, to generate a
copy
, the compiler has to know all fields. So, if it generated
copy
at the interface level, you would be forbidden to add new fields when implementing it. Since all implementations would necessarily be
data class
, and they cannot add any new fields, then all implementations are necessarily exactly the same, and thus the interface is useless since it already has a single useful implementation.
m
Wasn't too verbose, and probably depends on the number of classes and the number of properties in the interface. I imagine something could be automated with KSP, but I only needed it on one sealed hierarchy.
Theoretically this data interface would create a copy function and then the data class implementations would create their own overload with the extra parameters and the compiler would override the one in the interface. But I imagine this isn't needed often enough to add to the language
c
Maybe something like this will be added to value classes, since they are more likely to be used like this, but I don't see it being added to data classes.