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

如何在Kotlin的when语句各分支中执行函数foo()?

解决Kotlin中when语句每个分支执行公共函数的问题

你的写法错误是因为Kotlin的when语句语法要求每个分支必须是「匹配条件 -> 执行体」的形式,直接把foo()放在分支位置不符合语法规则。以下是几种正确的实现方式:

  • 手动在每个分支调用foo()
    这是最直接的方式,适合分支数量较少的场景:

    when(name) {
        "Sun" -> {
            print("Sun is a Star")
            foo()
        }
        "Moon" -> {
            print("Moon is a Satellite")
            foo()
        }
        "Earth" -> {
            print("Earth is a planet")
            foo()
        }
    }
    

    注意当执行体有多行代码时,需要用大括号{}包裹。

  • 提取公共逻辑,匹配分支后统一调用foo()
    如果只有匹配指定分支时才需要执行foo(),可以先处理分支逻辑,再统一调用函数:

    when(name) {
        "Sun" -> print("Sun is a Star")
        "Moon" -> print("Moon is a Satellite")
        "Earth" -> print("Earth is a planet")
        else -> return // 不匹配时直接返回,不执行foo()
    }
    foo()
    

    这种方式避免了重复写foo(),但要注意只有当name匹配三个值中的一个时,才会走到foo()的调用。

  • 封装公共执行逻辑函数
    当分支数量较多时,可以封装一个工具函数来复用「执行分支逻辑 + 调用foo()」的流程:

    // 封装公共函数
    fun executeWithFoo(block: () -> Unit) {
        block()
        foo()
    }
    
    // 使用when语句
    when(name) {
        "Sun" -> executeWithFoo { print("Sun is a Star") }
        "Moon" -> executeWithFoo { print("Moon is a Satellite") }
        "Earth" -> executeWithFoo { print("Earth is a planet") }
    }
    

    这种方式最大程度减少了重复代码,后续新增分支时只需调用executeWithFoo即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:24:41