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

Android/Kotlin中如何优化含重复分支的枚举返回函数逻辑

优化重复的when条件判断

你的代码存在嵌套条件判断和重复的type分支逻辑,我们可以通过前置过滤无效条件、合并状态与类型判断来简化代码,同时保持逻辑清晰。

方案1:简化嵌套,前置无效分支

先把shouldShowCTA为false的情况直接返回null,减少层级嵌套,再用外层when处理progress和completed状态,相比原代码减少一层嵌套:

if (!shouldShowCTA) return null

return when {
    progress -> when (type) {
        TYPE1 -> TYPE1_PROGRESS
        TYPE2 -> TYPE2_PROGRESS
        else -> null
    }
    completed -> when (type) {
        TYPE1 -> TYPE1_COMPLETED
        TYPE2 -> TYPE2_COMPLETED
        else -> null
    }
    else -> null
}

方案2:合并状态与类型,单个when处理所有情况

把progress/completed的状态和type组合成判断条件,用一个when覆盖所有有效映射,彻底消除重复的type分支:

if (!shouldShowCTA) return null

val currentState = when {
    progress -> "PROGRESS"
    completed -> "COMPLETED"
    else -> return null
}

return when (Pair(type, currentState)) {
    Pair(TYPE1, "PROGRESS") -> TYPE1_PROGRESS
    Pair(TYPE2, "PROGRESS") -> TYPE2_PROGRESS
    Pair(TYPE1, "COMPLETED") -> TYPE1_COMPLETED
    Pair(TYPE2, "COMPLETED") -> TYPE2_COMPLETED
    else -> null
}

如果觉得字符串标识不够严谨,可以定义内部枚举来表示状态:

private enum class State { PROGRESS, COMPLETED }

// 修改currentState赋值逻辑
val currentState = when {
    progress -> State.PROGRESS
    completed -> State.COMPLETED
    else -> return null
}

方案3:用映射表统一管理枚举映射

如果后续可能新增type或状态,用Map存储所有有效映射会更易于维护,新增情况只需在映射表中添加条目:

private enum class State { PROGRESS, COMPLETED }

// 统一管理所有枚举映射关系
private val enumMapping = mapOf(
    Pair(TYPE1, State.PROGRESS) to TYPE1_PROGRESS,
    Pair(TYPE2, State.PROGRESS) to TYPE2_PROGRESS,
    Pair(TYPE1, State.COMPLETED) to TYPE1_COMPLETED,
    Pair(TYPE2, State.COMPLETED) to TYPE2_COMPLETED
)

// 业务逻辑代码
if (!shouldShowCTA) return null

val currentState = when {
    progress -> State.PROGRESS
    completed -> State.COMPLETED
    else -> return null
}

return enumMapping[Pair(type, currentState)]

以上几种方案都能有效消除原代码中的重复逻辑,你可以根据团队编码习惯和后续扩展需求选择合适的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:36:20