A sealed interface in Kotlin is an interface that restricts its implementation hierarchy to a bounded set of types known strictly at compile time. By applying theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
sealed modifier to an interface, you dictate that all direct implementations must be declared within the same package and the same compilation module. This prevents arbitrary, external implementations by third-party clients.
Syntax and Declaration
A sealed interface is declared using thesealed keyword before the interface keyword. Its implementations can be standard classes, data classes, objects, or even other interfaces.
Core Rules and Constraints
- Compilation Boundary: All direct implementors of a sealed interface must be defined in the same package and the same module as the sealed interface itself. They do not need to be in the same file (as of Kotlin 1.5).
- Visibility: While the sealed interface itself can be
public, the compiler guarantees that no unknown implementations can exist outside the defining module. - Statelessness: Because it is an interface, a sealed interface cannot have a constructor or backing fields. It can only declare abstract properties and functions, or provide default implementations.
- Inheritance Flexibility: A single class or object can implement multiple sealed interfaces. This allows for intersection types and complex hierarchical compositions that are impossible with sealed classes due to single-inheritance limitations.
Compiler Exhaustiveness
The primary mechanical benefit of a sealed interface is compiler-enforced exhaustiveness inwhen expressions. Because the compiler knows all possible direct implementations, it can verify that every possible type is evaluated.
If a when expression is used as a statement or an expression, the compiler will throw an error if a branch is missing, eliminating the need for a fallback else branch.
Sealed Interface vs. Sealed Class
While both restrict inheritance hierarchies, they differ in structural capabilities:- Constructors: Sealed classes can have constructors and hold state (backing fields) shared across subclasses. Sealed interfaces cannot have constructors or backing fields.
- Multiple Inheritance: A Kotlin class can inherit from only one sealed class, but it can implement an unlimited number of sealed interfaces.
- Enum Integration: An
enum classcan implement a sealed interface, allowing enums to participate in a sealed hierarchy. Anenum classcannot inherit from a sealed class.
Master Kotlin with Deep Grasping Methodology!Learn More





