Sobes.tech
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:

    • sealed class restricts subclasses — all subclasses must be declared in the same file as the sealed class itself.
    • abstract class does not restrict inheritance — subclasses can be declared anywhere.
  • Usage:

    • sealed classes are convenient for representing a limited set of options (e.g., for when expressions without else).
    • abstract classes 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")
}
What are the main differences between classes… - sobes.tech