首页 > 解决方案 > Kotlin 从嵌套的 forEach 返回@forEach

问题描述

我想break在嵌套的 forEach 循环中进行类似的操作,以过滤我的 searchView 中的数据(如果数据内容在我的搜索中包含任何单词)。

val filtered = mutableListOf<EventEntity>()

rawDataList.forEach {data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@forEach // **There is more than one label with such a name in this scope**
        }
    }
}

我的情况是否存在优雅的解决方案?

标签: androidkotlinforeachbreak

解决方案


如果您遇到此错误并且无法使用内置函数修复它,您可以通过name@在块之前添加将自定义标签应用于 lambda:

rawDataList.forEach outer@{data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@outer
        }
    }
}

推荐阅读