https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

04/26/2022, 6:42 PM
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

Tim Oltjenbruns

04/26/2022, 6:46 PM
BackendEnv.values().map { it.humanReadableName }
enumValues<>
is for generic access
c

Colton Idle

04/26/2022, 6:57 PM
Thanks for teaching!
😁 1
e

ephemient

04/26/2022, 7:09 PM
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
3 Views