在Kotlin中使用values()和valueOf迭代枚举值 [英] Iterate enum values using values() and valueOf in kotlin

查看:2093
本文介绍了在Kotlin中使用values()和valueOf迭代枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是新手.任何人都可以举一个使用value和valueOf方法迭代枚举的示例吗?

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

这是我的枚举类

enum class Gender {
    Female,
    Male
}

我知道我们可以得到像这样的值

I know we can get the value like this

Gender.Female

但是我要迭代并显示Gender的所有值.我们怎样才能做到这一点?任何帮助都将不胜感激

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

推荐答案

您可以使用

You can use values like so:

val genders = Gender.values()

自Kotlin 1.1开始,还提供了一些辅助方法:

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

要将枚举名称映射到枚举值,请使用valueOf/

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

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

这篇关于在Kotlin中使用values()和valueOf迭代枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆