Hi All, Need a little help with something I have b...
# android
r
Hi All, Need a little help with something I have been struggling since days. Lets say I have a Extension function
Copy code
fun 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
Copy code
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.
a
what do you mean, T.toJSONString(), T is a bounded type here, it is not a variable of type T. You can call toJSONString() on object instances of type "Any?".
think about it, if you call T.toJSONString(), then what will "this" be in body of toJSONString()?
r
Thank you @Abhi for this great explanation. Got to learn something new. Just to expand on it a bit. Is there no way to make an object from it.
a
Your toStr() is an extension function on Response<MyResponse<T>>, so in this toStr(), the "this" refers to an object of type Response<MyResponse<T>> It depends on how you are using generics, without the definition of Response and MyResponse, one can't answer your question
r
Since
this
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