Junior — Middle
Have you used sealed classes in your projects?
sobes.tech AI
Answer from AI
Yes, in Kotlin projects for Android, I used sealed classes to model limited hierarchies of states or events. Sealed classes allow defining a set of subclasses known at compile time, which simplifies handling through when without needing to write an else branch.
Example of using a sealed class to describe loading states:
sealed class LoadState {
object Loading : LoadState()
data class Success(val data: List<String>) : LoadState()
data class Error(val error: Throwable) : LoadState()
}
fun handleState(state: LoadState) {
when(state) {
is LoadState.Loading -> println("Loading...")
is LoadState.Success -> println("Data received: ${state.data}")
is LoadState.Error -> println("Error: ${state.error.message}")
}
}
This helps make the code safer and more readable, especially when working with UI states or operation results.