What are the differences between Sealed Interface and Sealed Class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, sealed class and sealed interface are used to restrict inheritance hierarchies, allowing the declaration of a fixed set of subclasses or implementations known at compile time.
Main differences:
-
Sealed Class — a class that can have a limited number of subclasses. All subclasses must be declared in the same file as the sealed class (or within its scope). This is convenient for implementing hierarchies with a limited number of options, such as representing states or events.
-
Sealed Interface — similar to a sealed class, but for interfaces. It allows declaring an interface with a limited number of implementations. This is useful when you need to describe behavior that different classes can implement but want to restrict their set.
Example:
sealed class Result {
data class Success(val data: String) : Result()
object Error : Result()
}
sealed interface Shape
class Circle(val radius: Double) : Shape
class Rectangle(val width: Double, val height: Double) : Shape
Thus, sealed class is suitable when a base implementation with states is needed, while sealed interface is important when the contract part with a limited number of implementations is required. Both help the compiler check the completeness of when expressions and ensure type safety.