Search code examples
genericskotlinparcelabledata-class

Can I create a generic type in a kotlin data class?


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.


Solution

  • 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