https://kotlinlang.org logo
Title
c

crankup

01/30/2020, 9:14 AM
Hello everyone, I am learning Kotlin and I have a question about enum vs sealed classes. Should I use sealed when my enum constants needs diffferent constructors ? Should I always use sealed classes no matter what ...
👋 1
s

sindrenm

01/30/2020, 9:17 AM
Yeah, sealed classes work well when you have different constructors for your enums (they're different types, really). 👍
I still use enums for simpler things, but I'm not sure if there's a performance overhead for using sealed classes all the time.
c

crankup

01/30/2020, 9:19 AM
😄Thank you for your feedback. For the overhead, I have no idea I did not read the generated bytecode
s

sindrenm

01/30/2020, 9:42 AM
If you can use an enum for your situation, then I guess it's one of the “do whatever makes you feel good” situations. 😎
👍 1
e

Erik

01/30/2020, 10:15 AM
I can imagine, but I'm not sure about this one, that bytecode optimisation (R8) can perform better with enums than with sealed classes. Use enums when possible, but sealed classes if what you need can't be done with enums
d

Dariusz Rusin

01/30/2020, 10:34 AM
On other hand - do you really need to care about so low optimization factors? Only few kind of apps should be aware of that. Most of the apps from the code perspective should focus on code readibility in first place.
👍 3
j

Jan Lund

01/30/2020, 2:08 PM
You get an ordinal using regular enums but sealed classes are also nice together with when.
e

Erik

01/30/2020, 4:08 PM
Enums go well with
when
too!
j

Jan Lund

01/30/2020, 4:09 PM
Exactly