Lilly
04/07/2021, 2:01 AMinterfaces
and sealed classes
and noticed that both can be used to achieve the same. For example:
Profile.kt
interface Profile
AProfile.kt
class AProfile : Profile { }
BProfile.kt
class BProfile : Profile { }
With sealed class:
Profile.kt
sealed class Profile
class AProfile : Profile()
class BProfile : Profile()
Now I'm wondering what are the reasons to prefer one over the other?ephemient
04/07/2021, 2:05 AMsealed class
is exhaustive.
val name = when (profile) {
is AProfile -> AProfiles.getName(profile)
is BProfile -> BProfiles.getName(profile)
}
will compile if sealed class Profile
, but will not compile if interface Profile
ephemient
04/07/2021, 2:06 AMsealed interface Profile
will be possible as wellZach Klippenstein (he/him) [MOD]
04/07/2021, 3:23 AMZach Klippenstein (he/him) [MOD]
04/07/2021, 3:24 AMLilly
04/07/2021, 3:22 PMFor example, third-party clients can't extend your sealed class in their code. Thus, each instance of a sealed class has a type from a limited set that is known when this class is compiled.What would be a use case for this? Isn't it better to always keep your code extensible?
Lilly
04/07/2021, 3:24 PMephemient
04/07/2021, 3:43 PMephemient
04/07/2021, 3:45 PMZach Klippenstein (he/him) [MOD]
04/07/2021, 3:52 PMIsnât it better to always keep your code extensible?Nope! As with most absolutes đ Extensibility should be an explicit design choice. This is why Kotlin itself even defaults classes and methods to being final, instead of Javaâs open default. That practice is well documented (see Effective Java, I think the book is called). The use case specifically for sealed classes is for something like enums, but where different enum values have different parameters. In swift, the analogous concept is literally called âenums with associated valuesâ, which is very similar in design and use case to kotlinâs sealed classes. More generally, sealed classes give (some of) the functionality of tagged union types. Here are some more articles.
Lilly
04/08/2021, 1:10 PM