首页 > 解决方案 > 如果存在多个相同类型,如何返回特定的 lambda?(科特林)

问题描述

例如,当我有两个 forEach lambda 时,我想返回一个特定的,例如以下示例中的 thing1,而不是 thing0。如果我尝试以下操作,它会抱怨“在此范围内有多个标签具有这样的名称”

伪代码来解释我的问题:

thing0.forEach { _ ->
    thing1.forEach { _ ->
        // I'd like to return the thing1 forEach lambda, but the compiler
        // issues a warning that there are multiple forEach lambdas present.
        if (condition) return@forEach
    }
}

标签: kotlinjetbrains-ide

解决方案


解决了!为尼克·李(Nick Lee)为我指明正确的方向干杯!原来我可以做到以下几点:

thing0.forEach { _ ->
    thing1.forEach nameHere@{ _ ->
        // I'd like to return the thing1 forEach lambda, but the compiler
        // issues a warning that there are multiple forEach lambdas present.
        if (condition) return@nameHere
    }
}

推荐阅读