Home > Net >  Default argument not passed in body request
Default argument not passed in body request

Time:10-26

I got a request (used with kotlinx.serialization.Serializable):

@Serializable
data class Request(
    val a: String,
    val b: String,
    val c: String = "version"
)

Part of retrofit / API code where I use this:

@PUT(value = "path/to/endpoint")
suspend fun sendRequest(@Body request: Request): Response

override fun sendRequest(request: Request) =
    flow<Resource<Response, NetworkError>> {
        emit(Resource.Success(network.sendRequest(request)))
    }.catch {
        emit(Resource.Error(it.parseNetworkError()))
    }

The default parameter val c: String = "version" does not follow in the request.

However, if I pass it in while creating the Request it works. Or if I put a breakpoint inspecting it before the Request is sent.

So this works:

Request("test", "test", "version")

But not this:

Request("test", "test")

Is this the compiler being smart and omitting it or something? How can I prevent it from doing so?

CodePudding user response:

This appears to be by design. According to the kotlinx.serialization documentation...

Default values are not encoded by default in JSON. 
This behavior is motivated by the fact that in most real-life 
scenarios such configuration reduces visual clutter, and saves the 
amount of data being serialized.

If you want to turn it on for a property, you can annotate it with @EncodeDefault

@Serializable
data class Request(
    val a: String,
    val b: String,
    @EncodeDefault val c: String = "version"
)
  • Related