Kotlin enumerated class


Release date:2023-09-22 Update date:2023-10-13 Editor:admin View counts:340

Label:

Kotlin enumerated class

The most basic use of the enumeration class is to implement a type-safe enumeration.

Enumeration constants are separated by commas, and each enumeration constantis an object.

enum class Color{
    RED,BLACK,BLUE,GREEN,WHITE
}

Enumeration initialization

Each enumeration is an instance of the enumeration class, which 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 at 0. If you need to specify a value, you can use its constructor:

enum class Shape(value:Int){
    ovel(100),
    rectangle(200)
}

Enumerations also support declaring their own anonymous classes and corresponding methods, as well as methods that override the base class. Suchas:

enum class ProtocolState {
    WAITING {
        override fun signal() = TALKING
    },

    TALKING {
        override fun signal() = WAITING
    };

    abstract fun signal(): ProtocolState
}

If the enumeration class defines any member, use a semicolon to separate theenumeration constant definition in the member definition

Use enumeration constants

Kotlin enumeration class in has a compositing method that allows youto traverse the defined enumeration constant and get the enumeration constant by its name.

EnumClass.valueOf(value: String): EnumClass  //
Convert the specified name to an enumeration value.
If the match is not successful, a IllegalArgumentException
EnumClass.values(): Array<EnumClass>        // Returns an enumeration value in the
form of an array

Get information about enumerations:

val name: String //Get Enumeration Name
val ordinal: Int //Obtain the order in which enumeration values are
defined in all enumeration arrays

Example

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)

}

Since Kotlin 1.1, you can use the enumValues<T>() and enumValueOf<T>() function accesses constants in the enumerated classin 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
}

Powered by TorCMS (https://github.com/bukun/TorCMS).