kotlinx serialization with generic message wrapper

Viewed 519

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?

0 Answers
Related