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

Time:06-03

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)

CodePudding user response:

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)
  • Related