Part 09 / Topic 8 of 10
Enum classes: named instances, not just names
An enum class is a closed set of named instances — not subtypes the way sealed is —
and each instance can carry its own constructor arguments and share methods.
enum class OrderStatus(val label: String, val isOpen: Boolean) {
PLACED("Placed", true),
PACKED("Packed", true),
SHIPPED("Shipped", true),
DELIVERED("Delivered", false),
CANCELLED("Cancelled", false); // semicolon ends the entry list
fun badge(): String = if (isOpen) "[$label]" else label
}
[PLACED(0) -> [Placed], PACKED(1) -> [Packed], SHIPPED(2) -> [Shipped], DELIVERED(3) -> Delivered, CANCELLED(4) -> Cancelled]
valueOf("SHIPPED"): Shipped
valueOf("LOST") threw IllegalArgumentException
Parsed from free text: [PLACED, SHIPPED, null]
Still-open statuses: [PLACED, PACKED, SHIPPED]
Next action for PACKED: Hand to courier
OrderStatus.entries is the modern, allocation-free way to list every entry (the older
values() allocates a fresh array on every call). valueOf("LOST") throws
IllegalArgumentException because "LOST" isn't one of the five declared entries — the same
"closed set" guarantee sealed gave subtypes, applied to instances. A when over an enum is
exhaustive for exactly the same reason a when over a sealed type is.
Full program: examples/07_enum_classes.kt.
Done here? The practice set for Part 9 — including the solutions — is on the part page.