3

I have a backend that will always return either a "success" with some data, as in the json field field will be named success and have the data in it. Or it will return an error object in a json format. So I'd like to have some sort of BaseResponse, so when I use it I could do something like BaseResponse so the success will be mapped as a Person object.

So I was thinking of doing like this:

@Parcelize
data class BaseResponse<T>(
     val success: T? = null
) : Parcelable

But it says Type is not directly supported with Parcelize. Is there any way I can do this at all? Or do I need to write something custom? The calls etc are called using Retrofit and Gson as serializer.

Mikkel Larsen
  • 876
  • 2
  • 14
  • 26

1 Answers1

11

You can do so by requiring T to be an implementation of Parcelable, like this:

@Parcelize
data class BaseResponse<T: Parcelable>(val success: T? = null) : Parcelable
92AlanC
  • 1,327
  • 2
  • 14
  • 33
  • 4
    This does not compile with the error "non-static type variable T cannot be referenced from a static context" – Zakhar Rodionov Dec 18 '20 at 15:03
  • this solution is not working for me. Throws an error "non-static type variable T cannot be referenced from a static context". is there anything else? – Jaspal May 15 '21 at 10:48