Working with enum constants
Enum classes in Kotlin have synthetic methods for listing the defined enum constants and getting an enum constant by its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass
):
EnumClass.valueOf(value: String): EnumClass
EnumClass.values(): Array<EnumClass>
The valueOf()
method throws an IllegalArgumentException
if the specified name does not match any of the enum constants defined in the class.
You can access the constants in an enum class in a generic way using the enumValues<T>()
and enumValueOf<T>()
functions:
enum class Track {
ID,
ARTIST,
ALBUM,
TITLE,
GENRE
}inline fun <reified T : Enum<T>> getTrackInfo() {
// print out all the items
print(enumValues<T>().joinToString { it.name })
}inline fun <reified T : Enum<T>> getTrackInfo() = enumValues<T>().map { it }fun example(): List <Track> {
// return a list of all the items
getTrackInfo<Track>()
}
Every enum constant has properties for obtaining its name and position in the enum class declaration:
val name: String
val ordinal: Int
ref:
https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants