Kotlin如何减少嵌套if else 编写更简洁高效代码的实用方法
Kotlin 嵌套if-else优化方案
首先针对你给出的业务代码,最直接的优化方式是使用卫语句+空合并操作符消灭嵌套,优化后代码如下:
suspend fun setStoreImages(call: ApplicationCall) { val storeImagesMapper = call.receive<ArrayList<StoreImageMapper>>() // 提前校验空值,非法场景直接返回,无需走后续分支 val employeeEmail = getEmailFromJWT(call) ?: return call.respond(HttpStatusCode.BadRequest, "No employee email id passed") val errorStr = StoreApis.createStoreImages(storeImagesMapper, employeeEmail) // 无错误直接返回成功,剩下的最后分支统一处理错误 errorStr ?: return call.respond(HttpStatusCode.Created) call.respond(HttpStatusCode.BadRequest, errorStr) }
优化核心逻辑是把所有异常/非法前置判断都提前返回,不需要把正常逻辑包裹在else分支里,代码从上到下顺序执行,没有嵌套,可读性和可维护性都大幅提升。
除此之外还有多种常用的if-else优化方案,可以根据不同场景选择:
- 空安全作用域函数:如果只需要对非空值做后续操作,可以用
let/run替代非空判断分支,示例如下:
suspend fun setStoreImages(call: ApplicationCall) { val storeImagesMapper = call.receive<ArrayList<StoreImageMapper>>() getEmailFromJWT(call)?.let { email -> StoreApis.createStoreImages(storeImagesMapper, email) ?.let { err -> call.respond(HttpStatusCode.BadRequest, err) } ?: call.respond(HttpStatusCode.Created) } ?: call.respond(HttpStatusCode.BadRequest, "No employee email id passed") }
- when表达式替代多分支if-else链:多条件并列判断的场景,用when写法更简洁直观,示例如下:
// 优化前 fun getDiscountLevel(amount: Int): String { if (amount >= 10000) return "钻石级" else if (amount >= 5000) return "黄金级" else if (amount >= 1000) return "白银级" else return "普通级" } // 优化后 fun getDiscountLevel(amount: Int): String = when { amount >= 10000 -> "钻石级" amount >= 5000 -> "黄金级" amount >= 1000 -> "白银级" else -> "普通级" }
- 密封类+多态替代状态判断分支:如果是业务状态判断类的嵌套if-else,把状态封装为密封类,用when匹配分支,编译器还会自动校验分支完整性,避免漏判:
sealed class OrderState { object Pending: OrderState() object Paid: OrderState() object Shipped: OrderState() object Cancelled: OrderState() } fun handleOrderState(state: OrderState) = when(state) { OrderState.Pending -> notifyUserPay() OrderState.Paid -> prepareShipment() OrderState.Shipped -> sendDeliveryNotice() OrderState.Cancelled -> refund() }
- 策略模式处理复杂分支逻辑:如果每个分支的业务逻辑较重、代码量大,可以把每个分支封装为独立的策略实现类,运行时根据条件匹配对应的策略执行,彻底消除业务代码中的if-else分支。
内容的提问来源于stack exchange,提问作者Tarun Chawla
相关产品推荐
相关产品推荐

