When should I use `sealed interface` or `sealed cl...
# getting-started
j
When should I use
sealed interface
or
sealed class
?
l
My rule of thumb is to always use a
sealed interface
unless I need a constructor in the
sealed class
a
Most common use of a
sealed class
is to handle the states of a response
Failure/Success/Loading
e
sealed interface doesn't work with
@Serializable
at present, so I still default to
sealed class
unless there is a particular structure that can only be expressed as
sealed interface
👍 1
a
As @ephemient said, My go to approach is a sealed interface, unless I want to serialize then, I fallback to sealed class
e
that's the opposite of what I said :P
but that works too
https://github.com/Kotlin/kotlinx.serialization/issues/1576 is supposed to be fixed in Kotlin 1.6.20 so hopefully this won't be a necessary consideration in the future
s
another nice property of
sealed interface
is that its implementing classes can be data classes, which is why sealed interfaces is my default. (good to know about the serializable restriction!)
e
data class can subclass (sealed) classes too, that's not a distinction
👍 1
ł
with sealed interfaces the multi inheritance is allowed
e
yes, that would be the "unless there isa particular structure that can only be expressed as a `sealed interface`" in my previous message. but ultimately it's a mostly stylistic choice if you're not interoperating with Java