Does Kotlin have an option to get a list of all en...
# announcements
v
Does Kotlin have an option to get a list of all enums that are in a class. Not values, but names? I couldn’t find one. Then, through an extension function?
l
MyEnum.values().map { it.name() }
v
Wow. I didn’t expect it to be so easy and elegant 🙂 Thanks a lot!
l
You probably could extract that to a extension function if need that a lot
and even place that inside your enum Companion object (making it similar to a static method in Java)
Copy code
enum class MyEnum {
    A, B, C;

    companion object { 
        fun names() = values().map { it.name() }
    }
}

...
MyEnum.names()
v
It returns actually a String. Can it return the enum type?
l
Ah, then you want the value, don't you?
MyEnum.values().toList()
maybe ?
I thought you wanted the names
(of the constants)
Perhaps if you give us an example we can figure something out
v
MyEnum.values().toList()
this one looks like what I need. I thought that
value
is like ‘Enum value’ in this example -
ENUM_NAME("Enum value")
d
Enums are regular objects in Kotlin (like in Java).
ENUM_NAME
will be an instance of
MyEnum
.