what is the most kotlin idiomatic way to the follo...
# announcements
l
what is the most kotlin idiomatic way to the following, so the code stays clean
l
What's wrong with this approach?
p
if you don't have more code after the when block you can do:
Copy code
fun process(someEnum: Enum) = when(someEnum) { ... }
l
And in some cases I would advocate for going
fun Enum.process()
👆 1
m
Using
when
as an expression will also ensure it is checked for completion. A hidden gotcha with the Kotlin
when
. Depending on what 'callMethodx` does, it may make sense to convert this to sealed classes and polymorphism.
👍 1
l
Sealed class + polymorphism seems correct, but in this case I believe it might be overly-compless
l
It is just that I read in some book that using switch statements is bad and it is better to use polymorphism, but don't know how to do that with enum
l
Probably some KISS will be better here
l
getFunction(someEnum).callMethod()
l
Instead of using an Enum you could use a Sealed Class
l
@LeoColman how would you do polymorphism with enum?
l
You could either add the method to the enum class or use a sealed class
An enum can h ave a method, and each constant must implement it
l
k thanks
p
For very simple stuff Enum, for everything else Sealed Classes. I would avoid Enum polymorphism, even though you can Override a method per constant, constant Instances will be Unique, pretty much Singletons. If you put State in it be careful of sharing it.