Sealed classes help you group related types together in a safe way. They make your code easier to understand and handle different cases clearly.
Sealed classes in 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.
sealed class ScreenState { object Loading : ScreenState() class Content(val text: String) : ScreenState() object Error : ScreenState() }
sealed class Response { data class Success(val code: Int) : Response() data class Failure(val message: String) : Response() }
This program defines a sealed class LoginResult with three states. The handleLogin function uses a when expression to print messages based on the state.
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")) }
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.
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.
Practice
sealed class in Kotlin?Solution
Step 1: Understand sealed class inheritance
A sealed class restricts which classes can inherit from it, limiting subclasses to those defined in the same file.Step 2: Compare with other class types
Unlike open classes, sealed classes do not allow unlimited subclassing, ensuring all subclasses are known at compile time.Final Answer:
To restrict class inheritance to a fixed set of subclasses -> Option DQuick Check:
Sealed class = fixed subclass set [OK]
- Thinking sealed classes allow any subclass anywhere
- Confusing sealed classes with abstract classes
- Assuming sealed classes create anonymous classes
Result in Kotlin?Solution
Step 1: Recall sealed class declaration syntax
The keywordsealedprecedesclassfollowed by the class name and braces.Step 2: Check each option
sealed class Result {} matches the correct syntax. Options B and C have wrong keyword order. sealed interface Result {} declares a sealed interface, not a sealed class.Final Answer:
sealed class Result {} -> Option BQuick Check:
sealed class syntax = "sealed class Name {}" [OK]
- Swapping 'sealed' and 'class' keywords
- Using 'sealed interface' instead of 'sealed class'
- Omitting braces after class name
sealed class Response {
object Success : Response()
object Error : Response()
}
fun handle(response: Response) {
when(response) {
is Response.Success -> println("Success")
is Response.Error -> println("Error")
}
}
handle(Response.Success)Solution
Step 1: Identify the passed object type
The function is called withResponse.Success, which matches the first when branch.Step 2: Check the when branches
The when expression prints "Success" forResponse.Successand "Error" forResponse.Error.Final Answer:
Success -> Option CQuick Check:
Response.Success triggers "Success" print [OK]
- Confusing Success and Error outputs
- Forgetting to call the function with correct subclass
- Expecting compile error due to sealed class
sealed class State {}
class Loading : State()
class Success : State()
class Error : State()Solution
Step 1: Recall sealed class subclass rules
All subclasses of a sealed class must be declared in the same file as the sealed class.Step 2: Analyze the code snippet
The subclasses Loading, Success, Error are declared separately after the sealed class. This violates the rule because direct subclasses of a sealed class must be declared in the same file as the sealed class.Final Answer:
Subclasses must be declared inside the sealed class file -> Option AQuick Check:
Sealed subclasses must be in same file [OK]
- Declaring subclasses in different files
- Thinking sealed classes cannot have subclasses
- Confusing sealed classes with abstract classes
NetworkState having Loading, Success with data, and Error with message. Which is the best way to define Success and Error subclasses?Solution
Step 1: Understand subclass data needs
Success needs to hold data, and Error needs to hold a message, so they require properties.Step 2: Choose subclass type
Data classes are ideal for subclasses with properties because they provide equals, hashCode, and toString automatically.Final Answer:
Use data classes with properties inside the sealed class -> Option AQuick Check:
Data classes hold data in sealed subclasses [OK]
- Using object for subclasses needing data
- Using abstract classes unnecessarily
- Using interfaces instead of sealed subclasses
Ready to prove it?
Pass the test and this pattern moves unknown
