I have been reading about sealed classes and don’t really get why they would be needed.
Does anyone have a good example to explain how you would use them?
I have been reading about sealed classes and don’t really get why they would be needed.
Does anyone have a good example to explain how you would use them?
Have you checked the example given in the official documentation? What’s unclear about it?
The official example was too brief. That applies to a lot of the documentation actually, there is a lot of assumed knowledge.
I found a great example which explained it better at https://blog.simon-wirtz.de/sealed-classes-kotlin-explanation/ if anyone is confused by sealed classes.
How familiar are you with Java? One challenge is the Kotlin is starting to attract developers who have primary experience outside Java. It is a problem for our team as we have no java projects, only kotlin projects, and Kotlin documentation tends to assume java knowledge. Other than train devs on a language they will not learn, there is no path for learning kotlin. We have scaled back on kotlin for this reason.
The purpose is for you to know all possible direct subtypes of a type.
So, for example, if you are using it in a when expression:
when (something) {
is ThisType -> 0
is ThatType -> 42
}
You are sure covered all the cases. In a sense, they work like an enum, but more extensible.
With that in mind, why would you need enums in the language?
Well, I suppose enums are a lighter weight solution. And they map to Java enums, which you need to be able to represent in Kotlin.
I use sealed classes for events that might might contain varying kinds of data, which works really nice with kotlin’s smart casting capabilities.
e.g.
sealed class ScreenEvent
data class ItemSelected(val item: Item) : ScreenEvent()
data class TextEntered(val text: String) : ScreenEvent()
object BackButtonClick : ScreenEvent()
fun handleEvent(event: ScreenEvent) = when(event) {
is ItemSelected -> doSomethingWithItem(event.item)
is TextEntered -> doSomethingWithText(event.text)
BackButtonClick -> navigateBack()
}
You can’t easily do that with standard enums