Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a enum member by the ordinal value in kotlin?

Tags:

android

kotlin

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
like image 644
HelloCW Avatar asked Nov 16 '18 06:11

HelloCW


3 Answers

👷 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 }
like image 69
Westy92 Avatar answered Nov 03 '22 04:11

Westy92


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]
like image 37
Milind Mevada Avatar answered Nov 03 '22 04:11

Milind Mevada


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"

like image 2
Abhi Avatar answered Nov 03 '22 04:11

Abhi