10

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
  • 306
  • 16
  • 96
  • 224
  • 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

12

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
  • 2,929
  • 1
  • 13
  • 21
9

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
  • 15,421
  • 3
  • 63
  • 47
1

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
  • 388
  • 1
  • 11