Is there a difference between an enum and a sealed...
# getting-started
r
Is there a difference between an enum and a sealed interface that only contains objects? I wonder if sealed classes/interfaces make enums obsolete.
j
there are some differences, for example you can iterate the values of an enum but not the fields of a sealed class also an enum value is a class, so it can contain some fields to enrich it and finally, an enum allows you to work easily with
when
and enforces you to handle all the cases
đź’Ż 1
e
you can iterate
Parent::class.sealedSubclasses.map { it.objectInstance }
- there's an open issue to make it available without runtime reflection
when
works fine on objects (or any other subtype) of sealed classes and interfaces
today i learned 1
r
I’m not clear on “also an enum value is a class, so it can contain some fields to enrich it”, objects can also contain fields, right?
e
the bytecode generated is a bit different (makes usage from Java significantly different) and only enums can be used in annotations
otherwise I'd just go with whatever fits your usage better
j
Also, conceptually, a sealed class is an "enum" at the type level, while an enum is enumerated at the value level. Having only objects also makes this enumeration at the value level, but still there is this
e
the fact that all the enum values are the same type means they can't have different members or extensions
r
Oh, that’s a good point! Also the bit of only enums being allowed in annotations.
e
(enum values can override the same members differently though)
there's a little hopefully irrelevant implementation note:
Copy code
enum class Example {
    Foo {
        override fun toString(): String = "foo"
    },
    Bar
}
Example::class.java != Example.Foo::class.java
Example::class.java == Example.Foo.declaringClass
Example::class.java == Example.Bar::class.java
there's a sorta first party workaround, https://github.com/JetBrains-Research/reflekt/issues/71
s
TLDR: sealed classes are enums with superpowers
🚀 1
j
honestly, same here, sorry for the misleading comment earlier…
r
Neat, thanks!
104 Views