Iterate enum values using values() and valueOf in

2020-08-09 08:12发布

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

标签: kotlin
2条回答
【Aperson】
2楼-- · 2020-08-09 08:46

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")     
查看更多
【Aperson】
3楼-- · 2020-08-09 08:55

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
查看更多
登录 后发表回答