3.16. Kotlin enumerated class

发布时间 : 2025-10-25 13:34:26 UTC      

Page Views: 10 views

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 } 

3.16.1. 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

3.16.2. 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() and enumValueOf() 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 } 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。