ADT, enums vs sealed classes I am arguing with a c...
# announcements
e
ADT, enums vs sealed classes I am arguing with a collegue about using an
enum
or
sealed
. The scenario is I have implemented an enum and he is asking me to change to sealed, in the first wave of this discussion I was saying that instead of having a thing like:
Copy code
sealed class Days {
    object Monday: Days(),
    object Tuesday: Days(),...
is better to use just an enum He almost has convinced me when he complains about using
when
because with enum you have one type.. Thinking about ADTs in our application now I think the sealed class is the right way, it does matter all elements are `object`(singletons) in it. What’s your opinion?
a
Use an enum until you need anything more powerful.
4
☝️ 5
a
If they're all
object
- what's the point in having sealed classes? The beauty of sealed is that you can have "instances of enums with state" sort of thing, and still leverage Kotlin
when
etc. In the end though the code will effectively look the same, so the questions then are; - Is there a performance concern? I believe using sealed classes and a when statement is a bunch of "`instanceOf`" checks. - Or will you be serializing it? Enums are serializable, sealed classes are not (at least not that I'm aware of, without adding it yourself). - Also, small/personal nitpick, I feel like it should be
Day
, not `Days`;
if (someVar is Day) ...
In general I would say use enums though unless you need instances with their own states
3
p
He almost has convinced me when he complains about using
when
because with enum you have one type..
And? What’s wrong with that? 🙂
g
Is there a performance concern? I believe using sealed classes and a when statement is a bunch of "`instanceOf`" checks.
That's when you use
is
. With object you can skip
is
and the expected performance should be as good as with enums. That being said, if your sum type is always going to contain only singletons, enum declaration is cleaner.
p
Is you need parameters that will be different depending on the day use
sealed class
if not then use an
enum class
.
p
I'd definately use an enum. I assume you won't add new weekdays soon 😉
😂 2
e
Thanks all!