mardi 31 mai 2022

Is it possible to use all possible types from reflection as generic type?

I am trying to use reflection to automatically create savedStateHandle for some classes.

fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) = 
    when (this.returnType.javaType) {
        String::class.java -> handle.get<String>(this.name)
        Int::class.java -> handle.get<Int>(this.name)
        Uri::class.java -> handle.get<Uri>(this.name)
        else -> throw RuntimeException("Type not implemented yet")
    }

As you see IF the type is for instance String then I want the return type of get function to be String and when doing it this way I have to define every single case manually.

It would be nice if I could just do something like this.

fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) =
    handle.get<this.returnType.javaType>(this.name)




Aucun commentaire:

Enregistrer un commentaire