Search code examples
androidkotlinretrofit2

Optional parameter in retrofit method


I have 2 methods:

@POST("/example")
fun getSomething(@Body string: String)

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String)

Sometimes I have to post with header sometimes without, it works but in my opinion it could be one method especially with kotlin default args.

But something like:

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String = "")

will probably send also header but empty.

Is it possible to merge these 2 method into 1 ?


Solution

  • Define the header as nullable like this:

    @POST("/example")
    fun getSomethingWithHeader(
        @Body string: String, 
        @Header("YourHeader") header: String? = null
    )
    

    From https://square.github.io/retrofit/:

    If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.