Is there any smart way to achieve the following? ...
# reflect
g
Is there any smart way to achieve the following?
Copy code
class MyClass<E: Enum<E>>(val name?) {
    fun read(source: MagicalStringSupplier): E? = source.read()?.let { enumValueOf(it) }
}
I fully understand that the above example does not compile because the type of
E
is a class type parameter that gets erased during runtime. I fully appreciate that there is no way to reify
E
currently, but perhaps there's a more "dirty" way involving passing around a
KClass<E>
or (worst case) even a Java
Class<E>
? We badly need such a feature when reading configurations from files, so that we don't have to constantly convert strings to enums all the time 😇
i
You can pass
KClass<E>
or
Class<E>
to the primary constructor and then use it to get enum values with reflection. And to avoid providing it at the call site, you can introduce a reified top-level function
inline fun <reified E> MyClass(name) = MyClass(name, E::class)