You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求优化Kotlin中冗长的嵌套If语句

Kotlin嵌套If语句优化方案

优化后代码

// 提取重复的日志打印逻辑,仅满足条件时执行
Log.takeIf { locationType == 1 && isPostDayOfWeeks }?.let {
    Log.d("RefreshStatus", "PostLocation: $isPostLocation")
}

// 通过when表达式扁平化所有分支,用解构赋值统一参数
val (isEnabled, timeText) = when {
    locationType == 1 && isPostDayOfWeeks && isPostLocation -> 
        true to endTime.toString()
    locationType == 1 && isPostDayOfWeeks && !isPostLocation && isPostNextDayOfWeek() -> 
        false to startTime.toString()
    locationType != 1 && autoLocationSwitch -> 
        true to null
    else -> 
        false to null
}

settingRepo.setLocationStatusText(isEnabled, timeText)

优化说明

  • 消除重复代码:把原代码中两处重复的日志打印逻辑提取出来,用takeIf+let组合实现条件性执行,避免冗余。
  • 扁平化分支结构:用Kotlin的when表达式替代多层嵌套if,将所有条件分支转为平级结构,逻辑可读性大幅提升。
  • 简化参数传递:通过Pair解构赋值,把setLocationStatusText的两个参数统一计算后一次性传递,避免零散的方法调用。
  • 合并重复分支:将原代码中多处settingRepo.setLocationStatusText(false, null)的场景合并到else分支,精简代码行数。

内容的提问来源于stack exchange,提问作者Mayank Choudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:27:34