Kotlin如何实现方法可选链式调用 以FuelManager类使用场景为例
Kotlin可选链式调用实现方案
Kotlin完全支持该需求,针对FuelManager场景,有以下几种常用实现方式:
- 方案1:使用作用域函数实现(无侵入、适合单次使用)
借助apply作用域函数保持链式结构,结合空安全判断控制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)) .apply { payload?.let { body(it.toString()) } } .responseString()apply会始终返回当前请求对象本身,仅当payload不为空时才会调用body方法写入请求体,为空时直接跳过该步骤,完全不影响原有链式结构。 - 方案2:封装通用扩展函数(适合多场景复用)
你可以提前封装通用的可选调用扩展函数,所有支持链式调用的类都可以复用该逻辑:
使用时直接在链式调用中插入即可:// 定义通用扩展函数,条件成立时执行闭包逻辑 fun <T> T.optionalRun(condition: Boolean, block: T.() -> T): T { return if (condition) block(this) else this } // 适配可空参数的简化版本,参数不为空时执行闭包 fun <T, P> T.optionalRunIfNotNull(value: P?, block: T.(P) -> T): T { return value?.let { block(this, it) } ?: this }
逻辑说明:扩展函数内部已经完成了空判断或者条件校验,符合条件时才会执行闭包内的方法调用,否则直接返回原对象,代码可读性更高。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)) .optionalRunIfNotNull(payload) { body(it.toString()) } .responseString()
内容的提问来源于stack exchange,提问作者Leff
相关产品推荐
相关产品推荐

