Ritwik Raj Srivastava
03/28/2022, 6:12 AMfun Any?.toJSONString(): String {
return this?.let {
try {
val gson = GsonBuilder().setPrettyPrinting().create()
gson.toJson(this)
} catch (e: Exception) {
"{}"
}
} ?: "{}"
}
And I have another Extension function that takes in Generic T and I want to parse/manipulate the result. For example being
fun <T : Any> Response<MyResponse<T>>.toStr(): String {
return T.toJSONString()
}
I am getting this error
Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot
Please help me out. If anyone can explain the error itself. It will be great. I do not have indepth Kotlin know-hows.Abhi
03/28/2022, 7:16 AMAbhi
03/28/2022, 7:17 AMRitwik Raj Srivastava
03/28/2022, 10:50 AMAbhi
03/28/2022, 10:54 AMRonald Wolvers
03/28/2022, 9:15 PMthis
will in this case point to an object of type Response
you will have to traverse down to the object of type T
using functions defined on Response
and on MyResponse
as well. The type parameters on both would have to be marked out
(covariant) though or not use variance, otherwise it's not possible - as far as I'm aware - to define a function that returns an object of the type that is the type parameter. For example, a List
has a method get()
which returns an object of the type that is its type parameter, and so you would need a function like that too for both Response
and for `MyResponse`: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/#kotlin.collections.List