64

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

0

5 Answers 5

109

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")     
2
  • What is the order of iteration (by abc of name, or ordinal,...)? Is this method stable (iteration order doesn't change if enum order and items don't change)? Dec 3, 2020 at 16:15
  • 1
    See this Kotlin issue aiming to replace Enum.values() with a more modern and performant alternative.
    – Mahozad
    Dec 3, 2021 at 11:22
19

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
14

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
1
  • 2
    I was only able to get this to work if I added the method to the enum class' companion object. If you add the method directly to the enum class, you can only access it with Gender.Female.getList().
    – tronman
    Jan 2 at 20:07
4

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()

1

In Kotlin 1.9.0, the entries property is introduced as a replacement for the values() function

The entries property returns a pre-allocated immutable list of your enum constants. This is particularly useful when you are working with collections and can help you avoid performance issues.

enum class Gender {
    Female,
    Male
}

for (gender in Gender.entries) println(gender.toString())


Reference

https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.