簡體   English   中英

Kotlin 從嵌套的 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**
        }
    }
}

我的情況是否存在優雅的解決方案?

如果您遇到此錯誤並且無法使用內置 function 修復它,您可以通過在塊前添加name@將自定義標簽應用於 lambda:

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

似乎any擴展方法都是您正在尋找的。 從javadoc:

如果至少一個元素與給定的 [predicate] 匹配,則返回true

val filtered = rawDataList.filter { data ->
    text.split(' ').any { data.content.contains(it, ignoreCase = true) }
}.toMutableList()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM