https://kotlinlang.org logo
Title
d

Daniel Felipe Henao Toro

02/21/2023, 2:03 PM
Hi everyone, do you know whether there is a way to extract KClass from a type argument from generic class, for instance you have this code:
return exchangeWithRetry(
            budgetSplitterUrl,
            HttpMethod.PUT,
            budgetSplitter,
            XandrFlatResponse<XandrBudgetSplitter>()::class
        ).splits ?: emptyList()

fun <T> exchangeWithRetry(
   uri: String,
   method: HttpMethod,
   body: Any,
   responseClass: KClass<T>
) {
   //Here how can I know KClass of this class XandrBudgetSplitter from this complete XandrFlatResponse<XandrBudgetSplitter>()::class
}
If anyone knows how to do that, I really appreciate it. Thanks
j

Joffrey

02/21/2023, 2:19 PM
There is no such thing as the
KClass
for
XandrFlatResponse<XandrBudgetSplitter>
, because that expression is more general type, not just a class. Actually,
XandrFlatResponse<XandrBudgetSplitter>()::class
is a very strange way to get a class, and it already is just
XandrFlatResponse
, as if you had specified just
XandrFlatResponse::class
. The correct type to access the full type information would be
KType
d

Daniel Felipe Henao Toro

02/21/2023, 2:23 PM
Ok Joffrey thanks for guidance 🙂
j

Joffrey

02/21/2023, 2:24 PM
Here is an example using `KType`:
return exchangeWithRetry(
            budgetSplitterUrl,
            HttpMethod.PUT,
            budgetSplitter,
            typeOf<XandrFlatResponse<XandrBudgetSplitter>>,
        ).splits ?: emptyList()

fun <T> exchangeWithRetry(
   uri: String,
   method: HttpMethod,
   body: Any,
   responseType: KType,
) {
   val typeArg = responseType.arguments[0].type
   // ...
}
d

Daniel Felipe Henao Toro

02/21/2023, 2:25 PM
Ohh interesting, I will check this example thanks so much