Kotlin Enum Classes | Tutorial
Tutorial -- Learning is not just about technology, but also about dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
Kotlin Tutorial
Kotlin Tutorial Kotlin IntelliJ IDEA Environment Setup Kotlin Eclipse Environment Setup Kotlin Command Line Compilation Kotlin Android Environment Setup Kotlin Basic Syntax Kotlin Basic Data Types Kotlin Condition Control Kotlin Loop Control Kotlin Classes and Objects Kotlin Inheritance Kotlin Interfaces Kotlin Extensions Kotlin Data and Sealed Classes Kotlin Generics Kotlin Enum Classes Kotlin Object Expressions and Object Declarations Kotlin Delegation
Kotlin Object Expressions and Object Declarations
Kotlin Enum Classes
The most basic use of an enum class is to implement a type-safe enum.
Enum constants are separated by commas, and each enum constant is an object.
enum class Color{ RED,BLACK,BLUE,GREEN,WHITE }
Enum Initialization
Each enum is an instance of the enum class and can be initialized:
enum class Color(val rgb: Int) {RED(0xFF0000),GREEN(0x00FF00),BLUE(0x0000FF)}
The default name is the enum constant name, and the value starts from 0. If you need to specify a value, you can use its constructor:
enum class Shape(value:Int){ ovel(100), rectangle(200)}
Enums also support declaring their own anonymous classes and corresponding methods, as well as overriding base class methods. For example:
enum class ProtocolState { WAITING { override fun signal() = TALKING }, TALKING { override fun signal() = WAITING }; abstract fun signal(): ProtocolState}
If an enum class defines any members, a semicolon must be used to separate the enum constant definitions from the member definitions.
Using Enum Constants
Enum classes in Kotlin have synthetic methods that allow iterating over the defined enum constants and obtaining enum constants by their name.
EnumClass.valueOf(value: String): EnumClass // Converts the specified name to an enum value. Throws IllegalArgumentException if no match is found.
EnumClass.values(): Array<EnumClass> // Returns the enum values in an array.
Obtaining enum-related information:
val name: String // Gets the enum name.
val ordinal: Int // Gets the ordinal of the enum value in the array of all enum constants.
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>() functions to access constants in an enum class 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
}
YouTip