Get Moshi adapter from a generic Type - Kotlin

Viewed 1610

I'm trying to set up a Moshi adapter so that I can get any model that I pass as a generic. So far I'm having issues getting the class from T generic, IDE says Cannot use T as a reified type parameter. Use a class instead.

Any ideas how to solve this?

val model = getModel<SimpleModel>()    

private fun <T> getModel() : T? {
  val moshi = Moshi.Builder().build()
  val adapter = moshi.adapter<T>(T::class.java)
  return adapter.fromJson("{\"name\": \"this_guy\"}")
}

Thanks!

1 Answers

Use private inline fun <reified T> getModel(): T as your function declaration.

Declaring the type parameter as reified allows you to access its class object.

Related