Hi i'm trying to create extension for Any object t...
# getting-started
a
Hi i'm trying to create extension for Any object to be convert to json, This is related generics, where i'm stuck at adapter<T>() , it is not able to match any of the exsisting signatures it has. Can any one help. I'm using Moshi here.
*inline fun* <*reified* T> Any.toCoCJson() {
*val* moshi: Moshi = Moshi.Builder().build()
*val* jsonAdapter: JsonAdapter<T> = moshi.adapter<T>()
*val* json: String = jsonAdapter.toJson(*this as* T)
}
s
Moshi is expecting either a Java
Type
or a Java
Class
. Given a reified Kotlin type, you can get its corresponding Java class with
T::class.java
, or you can get the Java
Type
with
typeOf<T>().javaType
. Of those two options, the second one is probably better, as it should be able to preserve more information about the type. So:
Copy code
val jsonAdapter = moshi.adapter(typeOf<T>().javaType)
👀 1
✅ 1
I'm a bit unsure about the intent of this function, though. Why do you want to accept
Any
and then cast it to
T
?
a
*return* jsonAdapter.toJson(*this*)
This was giving a compiler error
return jsonAdapter.toJson(this as T)
wouldn't this be correct ?
s
It would normally make more sense to change the function signature so that it accepts
T
instead of
Any
, unless there's a reason you can't use that approach.
Copy code
inline fun <reified T> T.toCoCJson() { ... }
plus1 3
a
him, yes you are correct,
Thank you @Sam 🙂
s
Glad I could help!