if I want to create enums from strings, where the ...
# announcements
r
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
you could add a companion object with a
fun of(value: String)
Call would look like this
YourEnum.of("yourString")
a
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
}
Will print result in:
Copy code
println(Direction.EAST == enumOfName<Direction>("east"))
Prints "true"
Copy code
println(Go.YES == enumOfName<Go>("anyplace"))
Prints "false"
m