Sealed classes help you group related types together in a safe way. They make your code easier to understand and handle different cases clearly.
0
0
Sealed classes in Android Kotlin
Introduction
When you want to represent a fixed set of types, like states of a screen.
When you need to handle different results from a network call, like success or error.
When you want to make sure all possible cases are checked in a when expression.
When you want to avoid using many unrelated subclasses and keep types organized.
Syntax
Android Kotlin
sealed class Result { class Success(val data: String) : Result() class Error(val error: Throwable) : Result() object Loading : Result() }
A sealed class can have subclasses defined inside it or in the same file.
All subclasses must be known at compile time, so no new subclasses outside the file.
Examples
This sealed class represents three states of a screen: loading, showing content, and error.
Android Kotlin
sealed class ScreenState { object Loading : ScreenState() class Content(val text: String) : ScreenState() object Error : ScreenState() }
Here, Response can be either Success or Failure, each holding different data.
Android Kotlin
sealed class Response { data class Success(val code: Int) : Response() data class Failure(val message: String) : Response() }
Sample App
This program defines a sealed class LoginResult with three states. The handleLogin function uses a when expression to print messages based on the state.
Android Kotlin
sealed class LoginResult { object Success : LoginResult() class Error(val message: String) : LoginResult() object Loading : LoginResult() } fun handleLogin(result: LoginResult) { when(result) { is LoginResult.Success -> println("Login successful!") is LoginResult.Error -> println("Login failed: ${result.message}") LoginResult.Loading -> println("Loading...") } } fun main() { handleLogin(LoginResult.Loading) handleLogin(LoginResult.Success) handleLogin(LoginResult.Error("Wrong password")) }
OutputSuccess
Important Notes
Sealed classes improve safety by forcing you to handle all cases.
You can use sealed interfaces in Kotlin 1.5+ for similar behavior.
Sealed classes are great for representing state machines or result types.
Summary
Sealed classes group related types in one place.
They help handle all possible cases safely with when expressions.
Use them to represent fixed sets of states or results.