https://kotlinlang.org logo
#reflect
Title
# reflect
g

gregorbg

06/03/2019, 3:06 PM
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

ilya.gorbunov

06/04/2019, 6:37 PM
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)
4 Views