An enum class defines a fixed set of named values, such as the days of the week, order statuses or app themes. Using an enum instead of plain strings means the compiler catches typos and when can check that you’ve handled every case.
Page Contents
Defining an enum
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun main() {
val d = Direction.EAST
println(d)
println(d.name)
println(d.ordinal) // position, starting at 0
}Output:
EAST EAST 2
Why not just use strings?
var status = "shiped" // typo: no error, bug later var status2 = OrderStatus.SHIPPED // typo here wouldn't compile
With an enum, only the values you defined are possible.
Enums with when
when on an enum must cover every value (or have else). If you add a new value later, the compiler points out every when you need to update:
enum class OrderStatus { PLACED, PACKED, SHIPPED, DELIVERED, CANCELLED }
fun message(status: OrderStatus) = when (status) {
OrderStatus.PLACED -> "We've received your order"
OrderStatus.PACKED -> "Your order is packed"
OrderStatus.SHIPPED -> "On the way"
OrderStatus.DELIVERED -> "Delivered. Enjoy!"
OrderStatus.CANCELLED -> "Order cancelled"
}
fun main() {
println(message(OrderStatus.SHIPPED))
println(message(OrderStatus.DELIVERED))
}Output:
On the way Delivered. Enjoy!
Properties in enums
Each value can carry data through a constructor:
enum class Plan(val monthlyPrice: Int, val maxUsers: Int) {
FREE(0, 1),
PRO(299, 5),
TEAM(999, 50);
fun yearlyPrice() = monthlyPrice * 12
}
fun main() {
for (p in Plan.entries) {
println("${p.name}: ₹${p.monthlyPrice}/month, ₹${p.yearlyPrice()}/year, up to ${p.maxUsers} users")
}
}Output:
FREE: ₹0/month, ₹0/year, up to 1 users PRO: ₹299/month, ₹3588/year, up to 5 users TEAM: ₹999/month, ₹11988/year, up to 50 users
When an enum has functions or properties after the values, end the list of values with a semicolon (;).
Listing values: entries
entries gives you all the values as a list. It’s available from Kotlin 1.9 and replaces the older values():
enum class Size { SMALL, MEDIUM, LARGE }
fun main() {
println(Size.entries)
println(Size.entries.size)
println(Size.entries.map { it.name.lowercase() })
}Output:
[SMALL, MEDIUM, LARGE] 3 [small, medium, large]
From a string: valueOf
enum class Theme { LIGHT, DARK, SYSTEM }
fun main() {
println(Theme.valueOf("DARK"))
val saved = "dark"
val theme = Theme.entries.find { it.name.equals(saved, ignoreCase = true) } ?: Theme.SYSTEM
println(theme)
try {
Theme.valueOf("BLUE")
} catch (e: IllegalArgumentException) {
println("No such theme")
}
}Output:
DARK DARK No such theme
valueOf is case-sensitive and throws if the name doesn’t exist. To read a value that might be invalid (for example, from settings), search entries and fall back to a default.
Each value can behave differently
enum class Operation(val symbol: String) {
ADD("+") { override fun apply(a: Int, b: Int) = a + b },
SUBTRACT("-") { override fun apply(a: Int, b: Int) = a - b },
MULTIPLY("×") { override fun apply(a: Int, b: Int) = a * b };
abstract fun apply(a: Int, b: Int): Int
}
fun main() {
for (op in Operation.entries) println("6 ${op.symbol} 3 = ${op.apply(6, 3)}")
}Output:
6 + 3 = 9 6 - 3 = 3 6 × 3 = 18
Enums can implement interfaces
interface Labeled { val label: String }
enum class Priority(override val label: String) : Labeled {
LOW("Low"), MEDIUM("Medium"), HIGH("High")
}
fun main() {
val sorted = listOf(Priority.HIGH, Priority.LOW, Priority.MEDIUM).sorted()
println(sorted.map { it.label })
}Output:
[Low, Medium, High]
Enums are compared by their declaration order, so sorted() puts LOW first.
Enum vs sealed class
Use an enum when every value is a fixed constant with the same shape. When the different cases need different data (for example, Success(data) and Error(message)), use a sealed class, which is covered in the next lesson.
Common mistakes
- Forgetting the semicolon: values followed by members need
;after the last value. - Using
valueOfon user input: it throws on unknown or wrongly-cased names. Searchentriesinstead. - Storing
ordinalin a database: if you reorder the values, the numbers change. Storenameinstead.
Exercise
Create a TrafficLight enum where each light knows how many seconds it stays on and which light comes next, then simulate one cycle.
enum class TrafficLight(val seconds: Int) {
RED(30), GREEN(25), YELLOW(5);
fun next(): TrafficLight = when (this) {
RED -> GREEN
GREEN -> YELLOW
YELLOW -> RED
}
}
fun main() {
var light = TrafficLight.RED
repeat(4) {
println("${light.name} for ${light.seconds}s")
light = light.next()
}
}Output:
RED for 30s GREEN for 25s YELLOW for 5s RED for 30s
FAQ
What is an enum class in Kotlin?
A class with a fixed set of named values, like enum class Color { RED, GREEN, BLUE }.
How do I get all values of an enum in Kotlin?
Use EnumName.entries (Kotlin 1.9+). Older code uses values().
How do I convert a String to an enum?
EnumName.valueOf("NAME"), which throws if the name doesn’t exist, or entries.find { it.name == text } for a safe lookup.
