marlonlom
09/05/2022, 10:23 PMreified
in a function that, when using a generic function, shows a compiler error message?
The compile error message:
Cannot use 'T' as reified type parameter. Use a class instead.
Joffrey
09/05/2022, 10:26 PMmarlonlom
09/08/2022, 9:09 PMimport com.beust.klaxon.Klaxon
import okhttp3.ResponseBody
import retrofit2.Converter
class KlaxonResponseBodyConverter<T> constructor(
private val klaxon: Klaxon
) : Converter<ResponseBody, T> {
override fun convert(value: ResponseBody): T? {
var response: T? = null
response = klaxon.parse<T>(value.byteStream()) // Cannot use 'T' as reified type parameter. Use a class instead.
return response
}
}
Joffrey
09/08/2022, 9:27 PMconvert
function, T
is not reified, T
is a regular generic type parameter of the class itself. Therefore, the actual T
to use is not known at compile time in convert
. That's why you cannot call a function like Klaxon.parse
that uses a reified type parameter, because it is supposed to know from the call site at compile time what type it is.
Now, T
is also erased at runtime so you can't access it anymore at that point either. What you would need is to pass the KClass
itself when constructing KlaxonResponseBodyConverter
, store it as a property, and use another mechanism of Klaxon that takes a KClass
as input. I don't know Klaxon much, but it seems you could use klaxon.parser(theKClass).parse(StringReader(json))
or something like that. There might be more convenient alternatives, though, I really didn't search thoroughly.marlonlom
09/12/2022, 3:56 PM