Sealed hierarchies versus enums
In Kotlin, while enums are suitable for a fixed set of constants, sealed interfaces and classes provide a more flexible and powerful alternative, especially when dealing with a state machine-like scenario or when additional data needs to be associated with each state.
In Java, enums are often used to represent a fixed set of states and can be overloaded with functionality. Consider a pizza order tracking system:
enum class PizzaOrderStatus {
ORDER_RECEIVED, PIZZA_BEING_MADE, OUT_FOR_DELIVERY, COMPLETED;
fun nextStatus(): PizzaOrderStatus {
return when (this) {
ORDER_RECEIVED -> PIZZA_BEING_MADE
PIZZA_BEING_MADE -> OUT_FOR_DELIVERY
OUT_FOR_DELIVERY -> COMPLETED
COMPLETED -> COMPLETED
}
}
}
This approach is straightforward but limited in terms of scalability and flexibility.
Sealed interfaces in Kotlin allow for a more expressive representation of...