I'm storing enum members as strings in a list: how...
# getting-started
a
I'm storing enum members as strings in a list: how can I convert from string back to enum reference maintain membership?
c
Copy code
yourList.map { str -> YourEnum.entries.find { it.name == str } }
thank you color 1
e
what do you want to do if any of the strings aren't in the enum?
what Ivan wrote is equivalent to https://youtrack.jetbrains.com/issue/KT-42619
1
a
Return
null
and handle gracefully
e
what Ivan wrote then, or
Copy code
val enumNameToValue = YourEnum.entries.associateBy { it.name }
yourList.map { enumNameToValue[it] }
where reusing
enumNameToValue
can save some computation
1
👍 1
c
^ in a small enum (~5 elements),
entries.find {}
is probably still faster, and uses a lot less memory; but yeah if you have a big enum this is better
👌 1
👍 1