KOTLIN / CHAPTER 10
Interfaces and sealed alternatives
AdvancedRepresent interchangeable behavior and closed sets of outcomes.
By the end of this chapter
- Implement a capability interface
- Use a sealed hierarchy for outcomes
- Handle all alternatives in when
The idea
An interface describes a capability that several classes may provide. A client can call that capability through the interface while the concrete object supplies the implementation. Kotlin classes and methods are final by default, so inheritance from an ordinary class requires an explicit open declaration. Prefer an interface when clients need a behavior rather than a shared representation.
A sealed hierarchy models a controlled family of alternatives, such as success and failure. When all permitted alternatives are known, a when expression can handle each case explicitly and become exhaustive without a catch-all branch. This lets the compiler expose omissions when the model evolves. Store the data needed by each case on that case instead of using unrelated nullable fields.
sealed interface Outcome
data class Success(val count: Int) : Outcome
data class Failure(val reason: String) : Outcome
fun describe(result: Outcome): String = when (result) {
is Success -> "Saved ${result.count}"
is Failure -> "Failed: ${result.reason}"
}
fun main() { println(describe(Success(3))) }Saved 3
The is check selects Success and makes its count property available in that branch. Both permitted outcome cases receive an explicit interpretation.
Try it yourself
Model a cache result as Hit(value) or Miss and write an exhaustive description function.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING