Kotlin return@forEach 来自嵌套的 forEach
Kotlin return@forEach from nested forEach
我想在嵌套的 forEach 循环中做类似 break
的事情来过滤我的 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**
}
}
}
我的情况是否存在优雅的解决方案?
似乎 any
扩展方法就是您要找的。来自 javadoc:
Returns true
如果至少有一个元素匹配给定的 [predicate]。
val filtered = rawDataList.filter { data ->
text.split(' ').any { data.content.contains(it, ignoreCase = true) }
}.toMutableList()
如果您遇到此错误并且无法使用内置函数修复它,您可以通过在块前添加 name@
将自定义标签应用于 lambda:
rawDataList.forEach outer@{data ->
text.split(' ').forEach { word ->
if (data.content.contains(word, ignoreCase = true)) {
filtered.add(data)
return@outer
}
}
}
我想在嵌套的 forEach 循环中做类似 break
的事情来过滤我的 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**
}
}
}
我的情况是否存在优雅的解决方案?
似乎 any
扩展方法就是您要找的。来自 javadoc:
Returns true
如果至少有一个元素匹配给定的 [predicate]。
val filtered = rawDataList.filter { data ->
text.split(' ').any { data.content.contains(it, ignoreCase = true) }
}.toMutableList()
如果您遇到此错误并且无法使用内置函数修复它,您可以通过在块前添加 name@
将自定义标签应用于 lambda:
rawDataList.forEach outer@{data ->
text.split(' ').forEach { word ->
if (data.content.contains(word, ignoreCase = true)) {
filtered.add(data)
return@outer
}
}
}