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
👷 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 }
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]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With