2

So I have this class:

@Serializable
sealed class Message<out T>{
    @Serializable
    class Success<out T>(val value: T) : Message<T>()
    @Serializable
    class Error<out T>(val errorMessage: String) : Message<T>()
}

Which I want to use for every message I send from my server to client. I already had to change the following function because I cant figure out how to use serialization with generics

            post("create") {
                val userName = call.receive<String>()
                if (userName.isBlank()) {
                    call.respond(Message.Error<User>("Specify a username"))
                } else {
                    call.respond(Message.Success(User(userName)))
                }
            }

to

            post("create") {
                val userName = call.receive<String>()
                if (userName.isBlank()) {
                    val serializer = Message.Error.serializer(User.serializer())
                    val response = Message.Error<User>("Specify a username")
                    val responseString = stringify(serializer, response)
                    call.respond(responseString)
                } else {
                    val serializer = Message.Success.serializer(User.serializer())
                    val response = Message.Success(User(userName))
                    val responseString = stringify(serializer, response)
                    call.respond(responseString)
                }
            }

But now my client throws this error: java.lang.RuntimeException: Failed to invoke private com.kvw.letsgo.common.Message() with no args

How do I use generics right with serialization?

Typhaon
  • 828
  • 8
  • 27
  • 1
    To be more decisive about the response, would you please mention which framework are you using for network communication? – Mahdi Rajabi Mar 10 '20 at 20:07
  • I'm using ktor with kotlinx serialisation server side, and retrofit with gson (which I'm still able to change) client side – Typhaon Mar 11 '20 at 07:08

0 Answers0