Issue
Is there a way to chain optionally a method in Kotlin, like for example on a FuelManager
class, where I would like to have body method as an optional thing, so this would be a request with a body method:
val (_, response, data) = manager
.request(Method.POST, url)
.timeoutRead(2_000)
.timeout(1_000)
.header("Content-Type" to "application/json")
.header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
.body(payload.toString())
.responseString()
So, here I would like to check if payload exists, then I would add body method, if not I would not add body to a request. Request without body method.
val (_, response, data) = manager
.request(Method.POST, url)
.timeoutRead(2_000)
.timeout(1_000)
.header("Content-Type" to "application/json")
.header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
.responseString()
Solution
I agree with Sweepers comment, that apply
may be nicer to use here, e.g.:
val (_, response, data) = manager.apply {
request(Method.POST, url)
timeoutRead(2_000)
timeout(1_000)
header("Content-Type" to "application/json")
header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
if (!payload.isNullOrBlank())
body(payload.toString())
}.responseString()
Inserting an if
-statement is relatively straight-forward in that case.
If you can't trust that what you have follows fluent API best practice (i.e. returning the actual instance again), you may instead use also something as follows:
val (_, response, data) = manager
.request(Method.POST, url)
.timeoutRead(2_000)
.timeout(1_000)
.header("Content-Type" to "application/json")
.header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
.let {
if (!payload.isNullOrBlank()) it.body(payload.toString())
else it
}
.responseString()
I.e. putting the if
-statement inside the scope functions let
or run
.
Answered By - Roland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.