https://kotlinlang.org logo
#announcements
Title
# announcements
c

Czar

06/21/2017, 11:33 AM
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

spand

06/21/2017, 11:37 AM
Considered putting the
val commonProperties
on an interface ?
l

lupajz

06/21/2017, 11:47 AM
open val
in sealed class header would not work ? or maybe just use class instead of data
c

Czar

06/21/2017, 11:57 AM
@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

spand

06/21/2017, 12:07 PM
yes
Although isnt that equivalent to adding an abstract property to
Device
?
l

lupajz

06/21/2017, 12:13 PM
open, yes
c

Czar

06/21/2017, 12:14 PM
@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

darkmoon_uk

06/21/2017, 12:44 PM
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
.