Search code examples
androidgenericskotlinmoshikotlin-reified-type-parameters

Get ParameterizedType from reified generic type for Moshi type adapter


The given assertion will fail due to the error

Failed to find the generated JsonAdapter constructor for class GenericType

How do I get the proper type from the reified type T for Moshi?

The GenericType type is annotated with @JsonClass(generateAdapter = true) using the Kotlin codegen for Moshi using only Moshi.Builder().build().

I could generate ParameterizedType manually with

Types.newParameterizedType(GenericType::class.java, String::class.java)

where GenericType::class.java is given with T:class.java. But I don’t know how to get the String type parameter to generify the approach.

inline fun <reified T : Any> adapter() =
    moshi.adapter<T>(type<T>())

inline fun <reified T : Any> type() =
    T::class.java

assert(adapter<GenericType<String>>() != null)

Note that the adapter is available for any GenericType<T>, just not for the actual class GenericType::class.java without generic information.

So the following genericType would find an adapter as long as I know about G:

inline fun <reified G : Any> genericType() =
    newParameterizedType(GenericType::class.java, G::class.java)

This G is what I'm looking to find in type(), as T::class.java is just GenericType::class.java there.


Solution

  • Kotlin now provides an experimental typeOf<T>() function to return the KType of the reified type T. So the required code is as simple as:

    inline fun <reified T : Any> type() = typeOf<T>()