Questions about sealded class, in the sample here ...
# compose
p
Questions about sealded class, in the sample here https://developer.android.com/codelabs/basic-android-kotlin-compose-getting-data-intern[…]elabs%2Fbasic-android-kotlin-compose-getting-data-internet they declare a sealed class:
Copy code
sealed interface MarsUiState {
    data class Success(val photos: String) : MarsUiState
    object Error : MarsUiState
    object Loading : MarsUiState
}
why they use interface instead of class? why object for Error and Loading instead of class? object is a singleton.
s
I’d flip both your questions around. Why sealed class instead of sealed interface? Why class instead of object?
2
a
I’d also say that you first need to understand the use-cases of
sealed class
,
sealed interface
and `object`s. Refer to this https://kotlinlang.org/docs/sealed-classes.html#declare-a-sealed-class-or-interface
z
I think the only reason to use a sealed class is: 1. you’re on an old version of kotlin that doesn’t support sealed interfaces (I’m so sorry) 2. You need the whole sealed type to subclass a class.
If you used a class for children that don’t have parameters, you’d still be allocating a new one every time you need one. But that’s wasteful, because all instances would be identical. So using an object keeps the allocations at 1.