How to use `reified` in a function that, when usi...
# getting-started
m
How to use
reified
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.
j
Could you please share the code the gives this error?
m
@Joffrey hi, this is the code:
Copy code
import 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
  }

}
j
The problem in this case is that in the
convert
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.
👏 1
m
@Joffrey thanks, i'll check and fix the converter, would be fine if i mention that thing of the reified and the convert function in retrofit repos, but for now i must continue with the converter 🙂