DEV Community

Discussion on: Kotlin - The Good, the Bad and the Ugly

Collapse
 
cjbrooks12 profile image
Casey Brooks

Kotlin allows you to define properties in interfaces, and you can still implement interfaces in a data class. This frees you from the brittle design of duplicated properties (at least, in remembering to put them all in), and also solves the issue of wanting to use a data class as multiple types. I've tried this pattern out in my Dokka-to-JSON formatter and it works quite well, and is very robust.

I do not think the choice of data classes being final was an oversight. I think it was made very intentionally, in order to get you truly using data classes as pure data composed of other data. They are not in the same "class" of objects as normal objects, they are useful primarily for serialization, and its generally a good design to not have your code interact directly with a data class any way. You should abstract your code away from the structure of the serialized data into a format that works better with the business logic.

Thread Thread
 
martinhaeusler profile image
Martin Häusler

You should abstract your code away from the structure of the serialized data into a format that works better with the business logic.

Totally in agreement here. That's why a quick way for building serialization formats is a great benefit.

Kotlin allows you to define properties in interfaces, and you can still implement interfaces in a data class.

I must admit that I didn't think of this option yet. It would allow you to do all the inheritance you want on the interface level, and instantiate only the leaf classes. It also enforces the correct properties and types. Okay, granted, that seems reasonable. It does entail though that you need to write the interfaces and the data classes, and in a lot of cases there will be only one implementation for each interface (DTOs for example). Still, thanks for the heads-up. I'll consider this in the future.

Thread Thread
 
yuriykulikov profile image
Yuriy Kulikov

You can, of course, implement interfaces in data classes, but, in my opinion, compisition will always be a better way to do it. Want to avoid property duplication in your DTOs/value objects/whatever? Move the duplicated part to a new data class and use it as a property in another class. I have yet to see a use of inheritence which can be justified. Normally it is just a mess. Steer clear of it :-)