I have following case to model. There are devices,...
# announcements
c
I have following case to model. There are devices, all devices have some common set of properties, the rest of the properties wildly differ. I thought about using a sealed class hierarchy for them. E.g.
Copy code
data class CommonProperties(/*properties here*/)
sealed class Device(val commonProperties: CommonProperties)
data class Type1Device(commonProperties: CommonProperties, /*other properties*/): Device(commonProperties)
//...
You probably see the problem:
Data class primary constructor must have only property (val / var) parameters
. Any suggestions on how to improve the design of my hierarchy?
s
Considered putting the
val commonProperties
on an interface ?
l
open val
in sealed class header would not work ? or maybe just use class instead of data
c
@spand that does not change anything, same problem @lupajz you mean override in every device type? Dirty. Not using data of course would work, but then I don't get all the niceties of data classes 🙂
@spand did you mean something like this:```data class CommonDeviceProperties() sealed class Device { abstract val commonDeviceProperties: CommonDeviceProperties } data class Type1Device( override val commonDeviceProperties: CommonDeviceProperties, /*other properties*/ ) : Device()```
s
yes
Although isnt that equivalent to adding an abstract property to
Device
?
l
open, yes
c
@spand, yes it is, and I already changed it locally like that 🙂 Thanks for the suggestion! I'll see how it works out in the end.
Updated the snippet.
d
Members of a sealed class hierarchy don't have to be `data class`es, you could just have a regular class which would remove the need to compose the
commonProperties
in the way you've done, just use inheritance and put the properties in
Device
.