English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The most basic usage of enumeration classes is to implement a type-safe enumeration.
Enumeration constants are separated by commas, and each enumeration constant is an object.
enum class Color{ RED, BLACK, BLUE, GREEN, WHITE }
Each enumeration is an instance of the enumeration class, and they can be initialized:
enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) }
The default name is the enumeration character name, and the value starts from 0. If you need to specify a value, you can use its constructor:
enum class Shape(value: Int){ oval(100), rectangle(200) }
Enumerations also support declaring their own anonymous classes and corresponding methods, as well as overriding methods of the base class. For example:
enum class ProtocolState { WAITING { override fun signal() = TALKING }, TALKING { override fun signal() = WAITING ; abstract fun signal(): ProtocolState }
If the enumeration class defines any members, use semicolons to separate the enumeration constant definitions in the member definitions
Kotlin enumeration classes have synthetic methods that allow you to iterate over the defined enumeration constants and obtain enumeration constants by their names.
EnumClass.valueOf(value: String): EnumClass // Convert the specified name to an enumeration value, if the match is not successful, it will throw IllegalArgumentException EnumClass.values(): Array<EnumClass> // Return the enumeration values in the form of an array
Get enumeration-related information:
val name: String //Get the enumeration name val ordinal: Int //Get the order of the enumeration value defined in all enumeration arrays
enum class Color{ RED, BLACK, BLUE, GREEN, WHITE } fun main(args: Array<String>) { var color: Color = Color.BLUE println(Color.values()) println(Color.valueOf("RED")) println(color.name) println(color.ordinal) }
from Kotlin 1.1 Start, you can use enumValues<T>()
and enumValueOf<T>()
Functions access constants in enum classes in a generic way
:
enum class RGB { RED, GREEN, BLUE } inline fun <reified T : Enum<T>> printAllValues() { print(enumValues<T>().joinToString { it.name }) } fun main(args: Array<String>) { printAllValues<RGB>() // Output RED, GREEN, BLUE }