Home > Software engineering >  Finding an enum item by its attribute
Finding an enum item by its attribute

Time:10-30

I've got an enum in Kotlin:

enum class ParticleMode(val modeName: String) {
   ABOVEHEAD("abovehead"),
   BELOWHEAD("belowhead")
}

In my case, the user needs to be able to select items by typing a name. So, I need to be able to get ParticleMode.ABOVEHEAD by its modeName ("abovehead"), same for BELOWHEAD, etc. How can I get an enum item by its modeName value?

CodePudding user response:

You can filter all values from you enum like this:

fun returnEnumFromString(string: String): Test {
    return ParticleMode.values().first { it.modeName == string }
}
  • Related