I'm struggling with data classes and polymorphism. I want to benefit from the immutability, but still be able to update my state. For this, I'm hoping to be able to use the copy
function.
Let's give an example. I have this class hierarchy:
interface Aging {
val age : Int
}
data class Cheese (
override val age : Int
// more Cheese specific properties
) : Aging
data class Wine (
override val age : Int,
val grape : String
// more Wine specific properties
) : Aging
And now I want to be able to do something like this (but this does not work):
class RipeningProcess(){
fun ripen(products : List<Aging>) =
// Not possibe, no copy function on Aging
products.map { it.copy(age = it.age + 1) }
}
How can I create updated copies in a polymorphic way?
I've tried to give the interface a copy
function, but if the subtypes have additional properties they don't override the copy function.
It's frustrating since I know the subtypes have that property, but I cannot utilize that knowledge in the interface.