I was playing around with `interfaces` and `sealed...
# android
l
I was playing around with
interfaces
and
sealed classes
and noticed that both can be used to achieve the same. For example:
Copy code
Profile.kt
interface Profile

AProfile.kt
class AProfile : Profile { }

BProfile.kt
class BProfile : Profile { }
With sealed class:
Copy code
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?
đŸš« 1
e
sealed class
is exhaustive.
Copy code
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
👌 3
in Kotlin 1.5,
sealed interface Profile
will be possible as well
z
And the reason for that, code outside the current file (in <=kotlin 1.4) or module (>=kotlin 1.5) can’t extend a sealed class directly.
l
@Zach Klippenstein (he/him) [MOD] Form the link and in relation to what you wrote:
For 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?
@ephemient Sorry I do't get the intention behind your code. Can you please elaborate?
e
z
Isn’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.
l
Thanks for the detailed answer