enum class
enum class defines an enumeration type — a fixed set of named constants treated as a type. You can retrieve all enumerants or look one up by name using values(), valueOf(), and related functions.
Syntax
// Basic enum class
enum class EnumName {
CONSTANT1, CONSTANT2, CONSTANT3
}
// enum class with a property
enum class EnumName(val propertyName: Type) {
CONSTANT1(value), CONSTANT2(value)
}
Syntax / Properties
| Syntax / Property | Description |
|---|---|
| EnumName.values() | Returns an array of all enumerants. |
| EnumName.valueOf("name") | Returns the enumerant matching the given name. Throws an exception if the name does not exist. |
| enumerant.ordinal | Returns the zero-based index of the enumerant in declaration order. |
| enumerant.name | Returns the name of the enumerant as a string. |
| enumValues<T>() | Returns an array of all enumerants using a type parameter. |
| enumValueOf<T>("name") | Returns the enumerant matching the given name using a type parameter. |
Sample Code
// enum class representing days of the week
enum class DayOfWeek {
MON, TUE, WED, THU, FRI, SAT, SUN
}
// enum class with a property
enum class Color(val code: String) {
RED("#FF0000"),
GREEN("#00FF00"),
BLUE("#0000FF")
}
fun main() {
// Check name and ordinal.
val day = DayOfWeek.WED
println(day.name) // WED
println(day.ordinal) // 2
// Iterate using values().
for (d in DayOfWeek.values()) {
println("${d.ordinal}: ${d.name}")
}
// Retrieve an enumerant by name using valueOf().
val c = Color.valueOf("BLUE")
println(c.code) // #0000FF
// Combining with a when expression is handy.
val msg = when (day) {
DayOfWeek.SAT, DayOfWeek.SUN -> "Weekend"
else -> "Weekday"
}
println(msg) // Weekday
}
Overview
enum class provides a type-safe way to work with a fixed set of constants. Every enumerant automatically has a name property (the constant name as a string) and an ordinal property (its zero-based declaration index).
You can define constructor properties to give each enumerant a different value. Passing an unknown name to valueOf() throws an IllegalArgumentException, so when converting arbitrary strings consider using try-catch or filtering with enumValues().
If you find any errors or copyright issues, please contact us.