Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

Iterate enum values using values() and valueOf in kotlin

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

question from:https://stackoverflow.com/questions/44300410/iterate-enum-values-using-values-and-valueof-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...