-
Notifications
You must be signed in to change notification settings - Fork 23
Difference between Sealed class and Sealed Interface
Devrath edited this page Mar 8, 2024
·
1 revision
In Kotlin, both sealed classes and sealed interfaces are used to restrict the types that can be subclasses or implemented, respectively. However, there are some key differences between them:
-
Hierarchy Structure:
- Sealed Class: A sealed class can have multiple subclasses, and these subclasses are typically defined within the same file as the sealed class itself. Subclasses must be declared within the same file or a file that is nested in the same package. This makes it easy to define a closed hierarchy of related classes.
- Sealed Interface: A sealed interface, on the other hand, can have multiple implementations, but each implementation must be defined in the same file as the interface. This is similar to sealed classes in terms of encapsulating a closed set of types, but the focus is on interface-based hierarchies.
-
Usage:
- Sealed Class: Sealed classes are often used to represent a restricted hierarchy of types, such as different states or events in an application. They are particularly useful in combination with when expressions for exhaustive pattern matching.
- Sealed Interface: Sealed interfaces are used when you want to provide a limited set of implementations for an interface, and you want to control those implementations. This is helpful when you want to ensure that all possible implementations of an interface are known at compile-time.
Here's a simple example to illustrate the differences:
// Sealed class example
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
}
// Sealed interface example
sealed interface Operation {
fun execute(): String
}
class Addition : Operation {
override fun execute(): String = "Performing addition"
}
class Subtraction : Operation {
override fun execute(): String = "Performing subtraction"
}
In summary, sealed classes are used for hierarchies of related classes, while sealed interfaces are used for hierarchies of implementations for an interface, with both providing a way to restrict the set of possible types.