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

如何在Kotlin Elvis运算符中continue/break/return前执行代码?

Kotlin中Elvis表达式结合return/continue的问题

我有一段Kotlin代码原本运行正常:

fun foo(bar: Bar) {
    val bar2: Bar = bar.nullableThing ?: return
    // do something with bar2
}

但如果想在return执行前加一些逻辑(比如打印错误提示),改成下面的写法就报错:

fun foo(bar: Bar) {
    val bar2: Bar = bar.nullableThing ?: run { 
        println("Error!")
        return
    }
    // do something with bar2
}

报错信息:'return' is not allowed here

不过我的实际问题是出在continue语句上,之前没注意return的情况,下面是更贴近我真实场景的代码:

data class Item(val str: String?)

val items = listOf<Item>(Item("tag:a"), Item("tag:b"), Item(null), Item("tag:c"))

val taggedItems = mapOf<String, String>("a" to "ItemA", "b" to "ItemB")

fun main() {
    for (item in items) {
        val stringItem = item.str?.let {
            if (it.startsWith("tag:")) taggedItems[it.substringAfter("tag:")]
            else it
        } ?: run {
            println("Error: tag ${item.str} is invalid")
            continue
        }
        compute(stringItem)
    }
}

fun compute(itemStr: String) = println(itemStr)

报错信息:'break' or 'continue' jumps across a function or a class boundary

我尝试写了个辅助函数来绕开这个问题:

fun printError(item: Item): String? {
    println("Error: tag ${item.str} is invalid")
    return null
}

然后改成这样的写法:

... ?: printError(item) ?: continue

但这种写法实在太糟糕了,想知道有没有更好的解决办法。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:09:22