if I want to create enums from strings, where the string value does not correspond to the enum name, and I want to scope the function to the enum, and I do not want to create an extension function on
String?
, what is idiomatic kotlin for it?
b
Björn Mayer
05/15/2020, 1:16 PM
you could add a companion object with a
fun of(value: String)
Call would look like this
YourEnum.of("yourString")
a
andries.fc
05/15/2020, 3:35 PM
Your can try the following function:
Copy code
inline fun <reified E : Enum<E>> enumOfName(name: String): E? {
return E::class.java.enumConstants.firstOrNull { it.name.toLowerCase() == name }
}
Given the following enums:
Copy code
enum class Direction {
NORTH,
SOUTH,
WEST,
EAST
}
enum class Go {
YES,
NO,
MAYBE
}