Kotlin Enum Classes
Enum classes define a fixed set of constants, each of which is an instance of the enum class.
Compared with string or numeric constants scattered around, enums are type-safe and let the compiler check when branches.
Kotlin enums can also have constructor parameters, implement interfaces, and even give each constant its own method implementations.
Defining an enum class
Declare an enum with enum class, separate constants with commas, and no trailing semicolon is needed.
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
fun main
(
)
{
val color
=
RunoobColor.
RED
println
(
color
)
// Printing it directly gives the constant name
println
(
RunoobColor.
RED
.
name
)
// The name property
println
(
RunoobColor.
RED
.
ordinal
)
// ordinal starts at 0
}
RED
RED
0
Enum constants are singletons, so == is enough; no complicated checks beyond === are needed or advisable.
Enums with constructor parameters
An enum class can have a primary constructor, and each constant passes its own arguments at declaration.
This is handy for binding extra information to each constant, such as the numeric value of a color.
Example
// The primary constructor has two parameters and each constant passes different values
enum
class
RunoobColor
(
val rgb
:
Int, val hex
:
String
)
{
RED
(
0xFF0000,
"#FF0000"
)
,
GREEN
(
0x00FF00,
"#00FF00"
)
,
BLUE
(
0x0000FF,
"#0000FF"
)
}
fun main
(
)
{
// entries is the recommended way to iterate since Kotlin 1.9, explained in detail later
for
(
color in RunoobColor.
entries
)
{
println
(
"${color.name} decimal value ${color.rgb}, hex ${color.hex}"
)
}
}
RED 的十进制值 16711680,十六进制 #FF0000
GREEN 的十进制值 65280,十六进制 #00FF00
BLUE 的十进制值 255,十六进制 #0000FF
An enum class constructor is always private and cannot be declared public, so no new constants can be created from outside.
This is exactly where the enum semantics of a "fixed set of values" come from.
Anonymous classes and method overriding
Each enum constant can be followed by a pair of braces containing that constant's own class body.
Inside the class body you can override abstract methods as well as methods with a default implementation.
Example
enum
class
RunoobState
{
WAITING
{
override fun signal
(
)
:
RunoobState
=
RUNNING
override fun describe
(
)
:
String
=
"Waiting"
}
,
RUNNING
{
override fun signal
(
)
:
RunoobState
=
WAITING
override fun describe
(
)
:
String
=
"Running"
}
;
// When there are members, the constant list must end with a semicolon
// Abstract method: every constant must implement it
abstract
fun signal
(
)
:
RunoobState
// Method with a default implementation: constants may override it
open fun describe
(
)
:
String
=
"Unknown state"
}
fun main
(
)
{
println
(
RunoobState.
WAITING
.
describe
(
)
)
println
(
RunoobState.
WAITING
.
signal
(
)
.
describe
(
)
)
}
等待中
运行中
RunoobState.WAITING.signal() returns RUNNING, so the second print is "Running".
Note that the class body of each constant is followed by a comma or semicolon separating it from the next constant, just like ordinary enum constants.
Members and semicolon separation
As soon as an enum class defines any member, a semicolon must follow the constant list.
Such members include regular functions, properties, companion objects, and so on.
Example
enum
class
RunoobLevel
(
val score
:
Int
)
{
LOW
(
1
)
, MID
(
5
)
, HIGH
(
10
)
;
// The semicolon separates the constant list from the members
// A regular member function
fun isPass
(
)
:
Boolean
=
score
=
5
// A companion object is also a member and must come after the semicolon
companion object
{
fun fromScore
(
score
:
Int
)
:
RunoobLevel
=
entries.
firstOrNull
{
it.
score
==
score
}
?:
LOW
}
}
fun main
(
)
{
println
(
RunoobLevel.
HIGH
.
isPass
(
)
)
println
(
RunoobLevel.
LOW
.
isPass
(
)
)
println
(
RunoobLevel.
fromScore
(
5
)
)
}
true
false
MID
If the enum class has no members, the trailing semicolon may be omitted.
entries: replacing values() since Kotlin 1.9
Iterating over enum constants used to be done with values(); since Kotlin 1.9, entries is recommended instead.
Every call to values() copies a new array, whereas entries returns a read-only list view without repeated allocation.
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
fun main
(
)
{
// Recommended since Kotlin 1.9: entries returns a read-only EnumEntries
println
(
RunoobColor.
entries
.
joinToString
(
)
)
println
(
RunoobColor.
entries
.
size
)
println
(
RunoobColor.
entries
[
1
]
)
// Iterate and format the output
println
(
RunoobColor.
entries
.
joinToString
(
" "
)
{
"${it.ordinal}-${it.name}"
}
)
}
RED, GREEN, BLUE
3
GREEN
0-RED 1-GREEN 2-BLUE
entries is read-only and does not support add or remove, unlike the array returned by values().
| Comparison Item | values() | entries (since Kotlin 1.9) |
|---|---|---|
| Return Type | Array |
Read-only list EnumEntries |
| Each time you call | Copies out a new array | Returns the same read-only view without reallocating |
| Supports add/remove | Fixed length, elements are mutable | Completely read-only, no add/remove/modify |
| Converting to an array | Already an array | Call toTypedArray() when needed |
| Recommendation | Still usable, but considered the old style | Recommended style since Kotlin 1.9 |
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
fun main
(
)
{
// Old style: values() creates a new array on every call
println
(
RunoobColor.
values
(
)
.
joinToString
(
)
)
// New style (since Kotlin 1.9): entries is a read-only list view with no array allocation
println
(
RunoobColor.
entries
.
joinToString
(
)
)
// Convert from entries when an array is really needed
val array
:
Array
<
RunoobColor
=RunoobColor.
entries
.
toTypedArray
(
)
println
(
array.
size
)
// enumValues() has been deprecated since Kotlin 1.9.20, do not use it
// println(enumValues
}
RED, GREEN, BLUE
RED, GREEN, BLUE
3
Note:Do not write println(RunoobColor.values()) directly: it prints the array address, like [LRunoobColor;@1b6d3586. For readable output, use entries or joinToString().
name and ordinal
Every enum constant has two properties: name and ordinal.
name is the constant name, and ordinal is its position in the declaration list, starting at 0.
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
fun main
(
)
{
val color
=
RunoobColor.
GREEN
println
(
color.
name
)
// Constant name
println
(
color.
ordinal
)
// Zero-based position index
for
(
item in RunoobColor.
entries
)
{
println
(
"${item.ordinal} -> ${item.name}"
)
}
}
GREEN
1
0 -> RED
1 -> GREEN
2 -> BLUE
name is read-only and cannot be reassigned as in Java.
ordinal depends on declaration order: once you reorder constants, ordinals stored in historical data become misaligned, so do not use it for persistent storage.
valueOf and enumValueOf
When you need to look up an enum constant by name, use valueOf or its generic version enumValueOf.
A missing name throws IllegalArgumentException, so it is best to do a safe lookup on external input.
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
fun main
(
)
{
// valueOf: get a constant by name
val red
=
RunoobColor.
valueOf
(
"RED"
)
println
(
red
==
RunoobColor.
RED
)
// enumValueOf: the generic version, more general in form
val blue
=
enumValueOf
<
RunoobColor
(
"BLUE"
)
println
(blue.
ordinal
)
// Safe lookup: returns null if the name does not exist, avoiding an exception
val safe
=
RunoobColor.
entries
.
firstOrNull
{
it.
name
==
"PURPLE"
}
println
(
safe
?:
"No PURPLE"
)
}
true
2
没有 PURPLE
valueOf is case-sensitive, so writing "red" throws immediately; keep this in mind when parsing user input.
Combining with when
Enums and when are a natural pair: once all constants are covered, no else branch is needed.
Example
enum
class
RunoobColor
{
RED, GREEN, BLUE
}
// All constants are covered, so no else is needed when used as an expression
fun hex
(
color
:
RunoobColor
)
:
String
=
when
(
color
)
{
RunoobColor.
RED
->
"#FF0000"
RunoobColor.
GREEN
->
"#00FF00"
RunoobColor.
BLUE
->
"#0000FF"
}
fun main
(
)
{
println
(
hex
(
RunoobColor.
RED
)
)
println
(
hex
(
RunoobColor.
BLUE
)
)
}
#FF0000
#0000FF
Since Kotlin 1.6, a when statement with an enum subject warns about non-exhaustive branches; since Kotlin 1.7 this is an error.
After adding a new enum constant, every when that does not handle it reports an error immediately, making the required changes obvious.
Common questions
Below are a few common problems encountered when using enum classes.
Why does compilation fail once members are added
Most likely you forgot the semicolon at the end of the constant list.
As long as the enum class has a function, property, or companion object, the semicolon is required.
Can values() still be used
Yes, but since Kotlin 1.9 entries is recommended because it does not reallocate arrays.
enumValues() has been deprecated since Kotlin 1.9.20, so new code should not call it.
Can an enum inherit from another class
No. An enum class implicitly inherits Enum, so it can only implement interfaces and cannot extend another class.
When you need to carry different data, consider using a sealed class instead.
Can ordinal be stored in a database
Not recommended: ordinal depends entirely on declaration order, and reordering constants will corrupt historical data.
When you need a stable identifier, define your own code property and assign it explicitly.