List of sealed class objects


#1

I switched a feature from enum to a sealed class, which is great because now my objects can extend different interfaces depending on what they are.
There is only one drawback: I need the list of all objects. Using enum, I used MyEnum.values(), but now I am maintaining a list of all objects.
Here is a related topic on stack overflow: https://stackoverflow.com/questions/44784328/how-to-obtain-all-subclasses-of-a-given-sealed-class (Personally I prefer to maintain the list than using nested classes and reflection).

My suggestion is to add a “SealedClass.objects()” function that provides all “object” instances that extends the sealed class.

By the way, thanks for the great work with Kotlin, I love the language!
Romain


#2

This exists in kotlin reflection for 1.3: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/sealed-subclasses.html but I see your point in actually being able to get all subclasses without reflection. I’m not sure what the valid use cases are though. Remember that you can have infinite instances of a sealed parent, so a sealed class is not just a “better enum” it is actually a different beast with different uses.


#3

Here is my use case: I implement a game called 7 Wonders Duel.
There are 23 buildings in the Age I deck. All unique.
Buildings have different types. Types lead to different effects in the game.

Using Enum, the building type is a property of the building:
GARRISON(type = MILITARY)
I can easily get the enum values to shuffle the deck and start the game.

Using a Sealed class, all the building become “object” types. The building types are now classes or interfaces:
object Garrison: MilitaryBuilding
This looks a better object-oriented design to me, however, I need to maintain the list of all buildings somewhere to be able to shuffle the deck.

I know that sealed class offer much more features, but my use case here only requires a better enum :upside_down_face: So, if I could list all “object” instances of a sealed class, it would save me the trouble of listing it manually.

Does it looks like a valid use case to you?

Thanks,
Romain


#4

I can see your use case. As far as I know Java doesn’t allow enum instances (rather than the class) to implement interfaces. I’m not sure about Kotlin, but it could also be JVM limitation. Reflection will solve your issue sufficiently (it’s not that the list is on the hot path, and in that case you can cache it). There are ways in which you can probably work around the interface thing with enums, but they are not pretty.


#5

Agreed. I will keep going with the list rather than reflection because it does not change (you know, board game are great to implement because specifications does not change all the time :wink:)
If at any point you reconsider this feature inside the core project (without reflection), let me know!

Best regards,
Romain