Kotlin - 方法的条件链接

Lef*_*eff 3 kotlin

有没有办法在 Kotlin 中选择性地链接一个方法,例如在一个FuelManager类上,我希望将 body 方法作为可选的东西,所以这将是一个带有 body 方法的请求:

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()
Run Code Online (Sandbox Code Playgroud)

所以,在这里我想检查有效负载是否存在,然后我会添加 body 方法,如果不存在,我不会将 body 添加到请求中。不带 body 方法的请求。

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()
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 7

我同意 Sweepers 的评论,apply在这里使用可能会更好,例如:

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()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,插入if- 语句相对简单。

如果您不能相信您所拥有的内容遵循流畅的 API 最佳实践(即再次返回实际实例),您也可以使用以下内容:

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()
Run Code Online (Sandbox Code Playgroud)

即,将if- 语句放入作用域函数letrun.