No momento, você está visualizando Sealed interface

Sealed interface

Let’s break down sealed interface in Kotlin.

Interface

In Kotlin, an interface defines a contract. It specifies a set of properties and functions that implementing classes must provide.

  • Abstract by Nature: Interfaces themselves don’t contain any implementation code for their functions (though Kotlin interfaces can have default implementations for functions and concrete property accessors). They only define the “what,” not the “how.”
  • Multiple Inheritance: A class can implement multiple interfaces, allowing it to inherit and conform to various contracts.
  • Polymorphism: Interfaces are fundamental to achieving polymorphism, where you can treat objects of different classes that implement the same interface uniformly.

Example of a regular interface:

Sealed

The sealed keyword in Kotlin, when applied to a class or an interface, restricts its inheritance or implementation.

  • Controlled Hierarchy: It means that all direct subclasses (for sealed classes) or direct implementers (for sealed interfaces) must be declared in the same module and package as the sealed class/interface itself
  • Known at Compile Time: The key benefit is that the compiler knows all possible direct subtypes at compile time. Once the module is compiled, no new direct implementations or subclasses can be added to that module from outside.

Sealed interface (Putting them together)

A sealed interface combines these two concepts:

  • It defines a contract (like any interface).
  • It restricts its direct implementations to the same module and package.

Why use a sealed interface?

The primary advantage of a sealed interface (and sealed class) comes when used with when expressions, especially for representing a fixed set of possible states, events, or types.

  • Exhaustive when: When you use a when expression on an instance of a sealed interface (or class), the Kotlin compiler can check if you’ve covered all possible implementing types. If you haven’t, it will issue a warning or an error (depending on your settings and whether the when is used as an expression or a statement). This ensures that you handle every possible case, making your code more robust and preventing runtime errors due to unhandled types.
  • Type Safety and State Management: Excellent for representing a closed set of states in a state machine, different types of UI events, or various kinds of results from an operation (e.g., Success, Error, Loading).
  • Domain Modelling: Helps in creating very precise and self-documenting domain models where a particular concept can only manifest in a few predefined ways.

This makes your event handling type-safe and robust to changes.

Referencias