I want to get a list<String> of this enum cl...
# getting-started
c
I want to get a list<String> of this enum class.
Copy code
enum class BackendEnv(val humanReadableName: String) {
  STAGING("Staging"),
  PROD("Production")
}
How would you do it?
I tried this code
Copy code
inline fun <reified BackendEnv : Enum<BackendEnv>> listOfBackendEnv(): List<String> {
  return enumValues<BackendEnv>().map { it.humanReadableName }
}
but it didn't work. The above code was inspired by this https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants
t
BackendEnv.values().map { it.humanReadableName }
enumValues<>
is for generic access
c
Thanks for teaching!
😁 1
e
Copy code
inline fun <reified T : Enum<T>> enumNames() = enumValues<T>.map { it.name }
is where the generic version would be useful, but for your use case, it looks like you want that specific type, not a generic
👍 1
or
Copy code
interface HasHumanReadableName {
    val humanReadableName: String
}
enum class BackendEnv(override val humanReadableName: String) : HasHumanReadableName {
    STAGING("Staging"),
    PROD("Production")
}
inline fun <reified T> listOfHumanReadableNames(): List<String>
    where T : Enum<T>, T : HasHumanReadableName =
    enumValues<T>().map { it.humanReadableName }

println(listOfHumanReadableNames<BackendEnv>())
for example
3