Iterate enum values using values() and valueOf in kotlin

Viewed 45149

Am a newbie here. Can anyone give an example to iterate an enum with values and valueOf methods??

This is my enum class

enum class Gender {
    Female,
    Male
}

I know we can get the value like this

Gender.Female

But I want to iterate and display all the values of Gender. How can we achieve this? Anyhelp could be appreciated

4 Answers

You can add this method to your enum class.

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

And call

val genders = Gender.getList()
// genders 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()

Related