I'm having some trouble testing a KClass<T> ...
# getting-started
b
I'm having some trouble testing a KClass<T> for being an Enum, and then getting an equivalent to
Class<T Extends Enum<T>>
out of it. for example:
Copy code
fun <T : Any>test(valueType: KClass<T>) {
    when (valueType) {
        Enum::class -> {
            // How to get 'x' to be Class<T> where T extends Enum<T> ?
            val x = valueType.java
        }
        else -> TODO()
    }
}
val x = valueType.java as Class<Enum>
complains about the missing type argument for
Enum
valueType.java as Class<Enum<T>>
complains because it doesn't see
T
as within the required bounds
t
Copy code
fun <T : Enum<T>> test(valueType: KClass<T>)
is the equivalent of
Copy code
void <T extends Enum<T>> test(Class<T> valueType)
b
in my situation i'm unable to change the boundary on T...is there a way to force cast it?
(my real method must handle other values of T that aren't enums)
i figured there must be a way to force cast in the case i detect it as an enum, though, just haven't been able to sort out how to do it
d
does
valueType.java as Class<Enum<*>>
work?
b
it gets "closer", but still isn't what i need. i think i'll have to add more detail for my use case:
i have a generic method which takes in a value type
KClass<T>
and then, based on that type, returns an appropriate "getter" function which handles that type:
Copy code
override fun <T : Any> getterFor(valueType: KClass<T>): (String) -> T {
        return when(valueType) {
            Boolean::class -> { path -> config.getBoolean(path) as T }
            Number::class -> { path -> config.getNumber(path) as T }
            Int::class -> { path -> config.getInt(path) as T }
            Long::class -> { path -> config.getLong(path) as T }
            Double::class -> { path -> config.getDouble(path) as T }
            String::class -> { path -> config.getString(path) as T }
            Enum::class -> { path ->
                val c = valueType.java as Class<Enum<*>>
                config.getEnum(c, path) as T
            }
the
getEnum
method i'm trying to call has the following signature:
public <T extends Enum<T>> T getEnum(Class<T> enumClass, String path);
when i use
val c = valueType.java as Class<Enum<*>>
i get this error:
image.png