https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

althaf

12/14/2023, 8:23 AM
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

Sam

12/14/2023, 8:36 AM
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

althaf

12/14/2023, 8:38 AM
*return* jsonAdapter.toJson(*this*)
This was giving a compiler error
return jsonAdapter.toJson(this as T)
wouldn't this be correct ?
s

Sam

12/14/2023, 8:40 AM
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

althaf

12/14/2023, 8:41 AM
him, yes you are correct,
Thank you @Sam 🙂
s

Sam

12/14/2023, 8:42 AM
Glad I could help!