5

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.

Brett
  • 1,647
  • 16
  • 34

1 Answers1

1

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 :

SorrowBeaver
  • 88
  • 1
  • 4
  • Thanks for the reply, going through the guide, comments, and git issues you posted and will report back – Brett Jun 09 '21 at 00:39
  • Sorry it took so long, 5 day power failure due to severe storms in Melbourne. I looked at the guide, the comment, and the git issues and messed around with this until almost giving up. Then I just copy and pasted the code from the first link and it works. Need to learn what it does now, and adapt it to my GraphQL example. Thank you so much. – Brett Jun 15 '21 at 09:39
  • Just added Kapt to my project and Boom, can't say I wasn't warned. – Brett Jun 22 '21 at 05:15