Inferring the generic type of a generic?


#1

Is it possible to infer the generic type of a generic in a reified function? For example;

inline fun <reified T: List<U>> getListType() = U::class.java

I know I can do it this way;

inline fun <reified U, reified T: List<U>> getListType() = U::class.java

But I was wondering if it’s possible to extract the generic type of the generic in the first one, so it can just be called like getListType<ArrayList<String>> as opposed to getListType<String, ArrayList<String>().

The actual purpose of the function I’m trying to write isn’t to get the type of an element of an array, but the generic type of a deserializer.


#2

As far as I know it is not possible. The problem is that javas type erasure does delete all type information about generics at runtime. At runtime there is no difference between List<String> and List<Foo>.

I was thinking that you maybe could use reflection like this

inline fun <reified T: List<*>> getListType() = U::class.typeParameters[0]

but this does not seem to give any useful information (The result would be out E.)

btw you need to use a wildcard(*) instead of U if you dont’t have U as another type parameter.


#3

Ah, that’s a shame. Thanks anyway!