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

Kotlin中匹配多变量的解决方案:when语句不支持的替代方法

Kotlin多变量匹配when语句的替代方案

给你几个可行的解决办法:

1. 打包变量为组合类型

把input、state、previous_states打包成三元组(Triple)或者自定义数据类,让when可以直接匹配这个组合对象。

使用Triple快速实现

when (Triple(input, state, previous_states)) {
    Triple(KeyPower, PowerOff, matched) -> { /* 执行对应逻辑 */ }
    Triple(KeyPower, PowerOn, matched) -> { /* 执行对应逻辑 */ }
    // 针对列表通配场景,补充分支内判断
    is Triple<*, *, *> -> {
        if (first == KeyMenu && second == PowerOff && third is List<*> && third.size >=2 && third[0] == MainView) {
            /* 处理listOf(MainView, _)的情况 */
        }
    }
}

自定义数据类增强灵活性

如果需要更清晰的语义或者复杂匹配,自定义数据类会更好:

data class InteractionContext(
    val input: Key,
    val currentState: PowerState,
    val previousStates: List<View>
)

when (InteractionContext(input, state, previous_states)) {
    is InteractionContext -> {
        with(it) {
            when {
                input == KeyPower && currentState == PowerOff && previousStates == matched -> { /* 逻辑 */ }
                input == KeyMenu && currentState == PowerOff && previousStates.firstOrNull() == MainView -> { /* 逻辑 */ }
            }
        }
    }
}

2. 嵌套when分层判断

按input、state的优先级嵌套when,内层再处理previous_states的条件,结构更清晰:

when (input) {
    KeyPower -> {
        when (state) {
            PowerOff -> if (previous_states == matched) { /* 执行逻辑 */ }
            PowerOn -> if (previous_states == matched) { /* 执行逻辑 */ }
        }
    }
    KeyMenu -> {
        if (state == PowerOff && previous_states.take(2).first() == MainView) {
            /* 处理listOf(MainView, _)的情况,忽略第二个元素 */
        }
    }
    // 其他输入类型的分支
}

3. 直接使用when的条件分支

不用绑定变量,直接在when的每个分支里写多变量组合判断,这种写法最直接:

when {
    input == KeyPower && state == PowerOff && previous_states == matched -> { /* 执行逻辑 */ }
    input == KeyPower && state == PowerOn && previous_states == matched -> { /* 执行逻辑 */ }
    input == KeyMenu && state == PowerOff && previous_states.firstOrNull() == MainView -> { /* 处理listOf(MainView, _)的情况 */ }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:50:52