12

I know I can get the ordinal value of a enum member using the code Color.BLUE.ordinal.

Now I hope to get Color.Green when I know the ordinal value of a enum member, how can I do?

Code

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



var aOrdinal=Color.BLUE.ordinal //it's 2

val bOrdinal=3  //How can I get Color.Green
HelloCW
  • 843
  • 22
  • 125
  • 310
  • Same approach works as in java. https://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type – laalto Nov 16 '18 at 06:22

3 Answers3

15

Just use values() function which will return the Array of enum values and use ordinal as an index

Example

val bOrdinal=3

val yourColor : Color = Color.values()[bOrdinal]
Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
13

Safety first:

// Default to null
val color1: Color? = Color.values().getOrNull(bOrdinal)

// Default to a value
val color2: Color = Color.values().getOrElse(bOrdinal) { Color.RED }
Westy92
  • 19,087
  • 4
  • 72
  • 54
2

You can use Kotlin enumValues<>() to get it

Example

    enum class Color{
    GREEN,YELLOW
}

fun main(str:Array<String>){
    val c  = enumValues<Color>()[1]
   print("Color name is ${c.name} and ordinal is ${c.ordinal}")
}

Prints "Color name is YELLOW and ordinal is 1"

Abhi
  • 398
  • 1
  • 11