https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jason5lee

03/25/2022, 2:50 PM
When should I use
sealed interface
or
sealed class
?
l

Luke

03/25/2022, 2:52 PM
My rule of thumb is to always use a
sealed interface
unless I need a constructor in the
sealed class
a

Alejandro Rios

03/25/2022, 2:53 PM
Most common use of a
sealed class
is to handle the states of a response
Failure/Success/Loading
e

ephemient

03/25/2022, 3:26 PM
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

andylamax

03/25/2022, 11:48 PM
As @ephemient said, My go to approach is a sealed interface, unless I want to serialize then, I fallback to sealed class
e

ephemient

03/25/2022, 11:51 PM
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

Stephan Schroeder

03/28/2022, 7:10 AM
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

ephemient

03/28/2022, 4:27 PM
data class can subclass (sealed) classes too, that's not a distinction
👍 1
ł

Łukasz Gendek

03/29/2022, 9:12 AM
with sealed interfaces the multi inheritance is allowed
e

ephemient

03/29/2022, 3:49 PM
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
30 Views