Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate enum values using values() and valueOf in kotlin

Tags:

kotlin

People also ask

How do I get the enum value on Kotlin?

Get enum by value Kotlin First, you can use values() method of Enum to get all the enum constants of the enum class as an array. Next, you can find the enum constant by using its value. In the below code, Enum class has a variable rgb and each enum constant has a value associated with it.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


You can use values like so:

val genders = Gender.values()

Since Kotlin 1.1 there are also helper methods available:

val genders = enumValues<Gender>()

With the above you can easily iterate over all values:

enumValues<Gender>().forEach { println(it.name) }

To map enum name to enum value use valueOf/enumValueOf like so:

 val male = Gender.valueOf("Male")
 val female = enumValueOf<Gender>("Female")     

You're getting [LGender;@2f0e140b or similar as the output of printing Gender.values() because you're printing the array reference itself, and arrays don't have a nice default toString implementation like lists do.

The easiest way to print all values is to iterate over that array, like this:

Gender.values().forEach { println(it) }

Or if you like method references:

Gender.values().forEach(::println)

You could also use joinToString from the standard library to display all values in a single, formatted string (it even has options for prefix, postfix, separator, etc):

println(Gender.values().joinToString()) // Female, Male

You can add this method to your enum class.

fun getList(): List<String> {
    return values().map {
        it.toString()
    }
}

And call

val genders = Gender.getList()
// gender is now a List of string
// Female, Male

You can do this and get a new array of your enum type Gender

val arr = enumValues<Gender>()

and if you want a list of its, you can use the extension. toList()