Reputation: 1837
I am having trouble compiling a Serialization data class that is also a generic. I am very new to Android and Kotlin, but am an experienced iOS/Swift developer (don't hold it against me).
I am trying to set up a generic data class wrapper around a GraphQL Response that can return me either the T generic in a data field, or an error in the error field.
import kotlinx.serialization.Serializable
@Serializable
data class GraphQLResponse<T:Serializable> (
val errors : List<ErrorResponse>? = null,
val data : Map<String, T>? = null
) {
@Serializable
data class Location(
val line: Int? = 0,
val column: Int? = 0,
val sourceName: String? = null
)
@Serializable
data class ErrorResponse(
val locations: List<Location>? = null,
val errorType: String? = null,
val message: String? = null
)
}
Compiling this I get the following error:
java.lang.AssertionError: Couldn't load KotlinClass from /Users/brett/Development/Company/android/app/build/tmp/kotlin-classes/debug/com/company/company/network/GraphQLResponse.class; it may happen because class doesn't have valid Kotlin annotations
And also a bunch of warning around reflection.
Is what I am trying to do possible with Generics and Serialization? Do I need to write my own deserialisation methods ?
Any help and advice would be appreciated.
Upvotes: 6
Views: 2042
Reputation: 88
You need to provide a custom serializer for type T.
check this guide
(BTW, in your code type T shouldn't be Serializable - T:Serializable
. It's just annotation)
There is a similar question, check this out. However, as you can see it may not work well if you use kapt in your project even you provide the serializer.
I found this comment from the serialization repository :
However, due to the mentioned kapt issue, it's impossible for now. Probably, a viable workaround can be to move models and serializers to the separate Gradle module, which is not processed by kapt.
And there are more issues about this problem :
Upvotes: 1