mama
mama

Reputation: 2227

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)

Upvotes: 0

Views: 57

Answers (1)

Karsten Gabriel
Karsten Gabriel

Reputation: 3652

You need a type parameter for the return type of the property. Then you can use that type parameter to specify the desired return type of get:

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

Upvotes: 1

Related Questions