Careeroza
Enum Basics
A Fixed Set of Values
An enum class defines a type with a fixed list of values: days of the week, order statuses, payment modes. Using an enum instead of strings like "pending" prevents typos and lets the compiler check your when expressions.
Example
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun main() {
val d = Direction.EAST
println(d) // name
println(d.name)
println(d.ordinal) // position, starting at 0
println(Direction.entries) // all values (Kotlin 1.9+)
println(Direction.valueOf("WEST")) // from a string
}Output
EAST EAST 2 [NORTH, SOUTH, EAST, WEST] WEST
Parsing Safely
Example
valueOf throws for unknown names. For user or server input, search the entries instead.
enum class Size { S, M, L, XL }
fun parseSize(text: String): Size? = Size.entries.find { it.name.equals(text, ignoreCase = true) }
fun main() {
println(parseSize("xl"))
println(parseSize("XXL"))
println(enumValues<Size>().joinToString())
}Output
XL null S, M, L, XL