Sealed classes are a powerful feature in Kotlin that allow you to define a restricted class hierarchy. This means that you can create a class that can have a limited number of subtypes, making it easier to represent a fixed set of types. Sealed classes help in ensuring type safety and improve code readability, especially when used with 'when' expressions. They are particularly useful in scenarios where you want to represent different states or outcomes, such as in a network response handling.
sealed class Result{ data class Success (val data: T) : Result () data class Error(val exception: Exception) : Result () object Loading : Result () } fun fetchData(): Result { // Simulating a network call return Result.Success("Data fetched successfully") } fun handleResult(result: Result ) { when (result) { is Result.Success -> println(result.data) is Result.Error -> println("Error: ${result.exception.message}") Result.Loading -> println("Loading...") } }