Given an enum class, how do I get its entries with...
# getting-started
b
Given an enum class, how do I get its entries without reified types?
Copy code
enum class Values { TEST }
fun <T: Enum<T>> x(clazz: Class<Enum<T>>) = clazz.entries
x(Values::class)
I'm passing it to a superclass so I can't inline Edit: My goal is to have an interface or some kind of base class that allows me to serialize/deserialize any enum from/to lowercase strings of its name
1
j
Not sure I get your goal, do you want to serialize an enum value? Or all enum values of a given enum class?
It would be nice to share a bit more of your actual code to see the context and what you're lacking
b
basically I want to pass an enum class to a super class that automatically serializes it from a string
I need to interact with JS string enums, so I'm looking at 'test' | 'test2' | 'test3'
I want to parse these onto and from kotlin enums
I ended up with
Copy code
inline fun <reified T : Enum<T>> fromCamelCase(value: String): T? =
    enumEntries<T>().find { it.name == value.toEnumConstant() }

fun <T : Enum<T>> Enum<T>.toCamelCase(): String =
    name.split("_").joinToString { it.lowercase() }
but obviously you can't make that work in super classes because of the reified type parameter
so the idea is to create super methods that parse these onto typesafe values, e.g.
Copy code
abstract class BaseApp<E: Enum<E>>(
    events: E
) {
    fun onEvent(event: String) {
        onTypedEvent(parseSomehow(event))
    }
    
    fun onTypedEvent(event: E) {} 
}
I'm not sure if you can inline super classes and even if you could, it would blow up bundle size
j
Ah so you want to serialize values of the enum, not the enum class as a whole. I might be stating the obvious, but why not use a serialization library and avoid the trouble?
b
not sure if that is too heavy to just turn a JS string into an enum
I've not yet pulled in serialization into my bundle
j
But you're already creating layers of abstraction and passing class objects around. The simplest approach is to just use a simple function with reified type whenever you need it, but you don't seem to be ok with that one.
Otherwise, one option is to build what you need at the moment you instantiate your class. Instead of passing the enum class, you could pass
entries
, or build a simple map to map string values to your enum instances
b
that would be fine, but the reified type parameter sort of limits it's use cases
I'll go with that
maybe this is a std lib API issue in that case?
there seems to be special machinery for enums that works differently
anyways, thank you for taking your time
p
You can make global map KClass -> Entries. At the start of app register needed enum classes.
❤️ 1