Kotlin Enum Classes
An enum class defines a fixed set of named constants. Use enums when a variable should only ever hold one of a specific, known set of values — like days of the week, directions, or status codes.
Basic Enum
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun main() {
val heading = Direction.NORTH
println(heading) // NORTH
println(heading.name) // NORTH (as String)
println(heading.ordinal) // 0 (index position)
}Enum in when Expression
enum class Season { SPRING, SUMMER, AUTUMN, WINTER }
fun describe(s: Season): String = when (s) {
Season.SPRING -> "Flowers bloom"
Season.SUMMER -> "Hot and humid"
Season.AUTUMN -> "Leaves fall"
Season.WINTER -> "Cold and snowy"
}
fun main() {
Season.values().forEach { println("${it.name}: ${describe(it)}") }
}Output:
SPRING: Flowers bloom
SUMMER: Hot and humid
AUTUMN: Leaves fall
WINTER: Cold and snowyEnum with Properties
enum class Planet(val radiusKm: Double, val massKg: Double) {
MERCURY(2_440.0, 3.30e23),
VENUS (6_052.0, 4.87e24),
EARTH (6_371.0, 5.97e24),
MARS (3_390.0, 6.42e23);
val gravity: Double
get() = 9.8 * (massKg / 5.97e24) / ((radiusKm / 6_371.0) * (radiusKm / 6_371.0))
}
fun main() {
Planet.values().forEach {
println("${it.name}: gravity = ${"%.2f".format(it.gravity)} m/s²")
}
}Enum with Functions
enum class TrafficLight {
RED {
override fun action() = "Stop"
override fun next() = YELLOW
},
YELLOW {
override fun action() = "Slow down"
override fun next() = GREEN
},
GREEN {
override fun action() = "Go"
override fun next() = RED
};
abstract fun action(): String
abstract fun next(): TrafficLight
}
fun main() {
var light = TrafficLight.RED
repeat(6) {
println("${light.name}: ${light.action()}")
light = light.next()
}
}Output:
RED: Stop
YELLOW: Slow down
GREEN: Go
RED: Stop
YELLOW: Slow down
GREEN: GoEnum Utility Functions
enum class Status { PENDING, ACTIVE, SUSPENDED, CLOSED }
// Get all values
println(Status.values().toList())
// [PENDING, ACTIVE, SUSPENDED, CLOSED]
// Get by name (case-sensitive)
val s = Status.valueOf("ACTIVE")
println(s) // ACTIVE
// Safe lookup using enumValueOf
val safeStatus = runCatching { Status.valueOf("INVALID") }
.getOrDefault(Status.PENDING)
println(safeStatus) // PENDINGPractical Example: Order Status Tracker
enum class OrderStatus(val displayName: String, val isFinal: Boolean) {
PLACED ("Order Placed", false),
CONFIRMED ("Confirmed", false),
SHIPPED ("Shipped", false),
DELIVERED ("Delivered", true),
CANCELLED ("Cancelled", true);
fun next(): OrderStatus? = when (this) {
PLACED -> CONFIRMED
CONFIRMED -> SHIPPED
SHIPPED -> DELIVERED
else -> null // final states have no next
}
}
fun main() {
var status = OrderStatus.PLACED
while (status != null) {
println("Status: ${status.displayName}")
if (status.isFinal) break
status = status.next() ?: break
}
}Output:
Status: Order Placed
Status: Confirmed
Status: Shipped
Status: Delivered