Junior — Middle
What are the main differences between classes declared with the keywords sealed and abstract?
sobes.tech AI
Answer from AI
Main differences between sealed and abstract classes in Kotlin:
-
Inheritance:
sealedclass restricts subclasses — all subclasses must be declared in the same file as thesealedclass itself.abstractclass does not restrict inheritance — subclasses can be declared anywhere.
-
Usage:
sealedclasses are convenient for representing a limited set of options (e.g., forwhenexpressions withoutelse).abstractclasses are used to create base classes with partial implementation.
-
Instantiation:
- Neither class can be instantiated directly.
Example of using a sealed class:
sealed class Result {
data class Success(val data: String) : Result()
object Error : Result()
}
fun handle(result: Result) = when(result) {
is Result.Success -> println("Data: ${result.data}")
Result.Error -> println("Error occurred")
}