'Is there a better way to EXTEND a DATA class into multiple sub classes in Kotlin

Let us suppose we have some data classes like following:

data class Order(
orderId: String,
payment: Payment,
customer: String,
...)

data class Payment(
total: BigDecimal,
date: ZoneDateTime,
...) 
{
fun getTotal() = total
}

I want to create new types of Order, let's say OrderYellow and OrderBlue to have different new custom fields and also has the possibility to re-override for example the getTotal() method of Payment data class

One way could be a "Java" oriented implementation

abstract class SuperOrder {
abstract val baseOrder: Order,
}

data class OrderYellow(
override var baseOrder: Order,
val status: String,
) : SuperOrder()

data class OrderBlue(
override var baseOrder: Order,
val createdBy: String,
) : SuperOrder()

In my application it is impossible to implement proper inheritance from scratch, since the usage of the Order class is too much spread all over the code base, making impossible a refactor in that sense, hence the above proposed solution seemed to be the best one for the sake of preserving as much existing code as I can. I also used a lot of time the copy method to maintain immutability of the object and manage the updates on the fields during the completion of the order.

In fact this is a good solution, but in this way I still have the problem that I can't override the getTotal() method of the nested class.

Do you have some ideas? Are there better ways to do it in Kotlin oriented code? Thanks a lot!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source