本文介绍了'返回'不会在Kotlin中脱颖而出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此Kotlin代码,为什么 return @ forEach 不会跳出 forEach ?它继续循环直到完成为止,删除reversed()不能解决问题:

I have this Kotlin code, why return@forEach doesn't jump out of forEach? It continues the loop until it finishes, removing reversed() doesn't solve problem:

rendered_words.reversed().forEach  { rw ->
                    if (rw.y - the_top > 0 && rw.y - the_top < height) {
                        new_top = rw.y
                        return@forEach
                    }
                }
                smoothScrollTo(Math.min(text_y - height, new_top))

我尝试将 return @ forEach 替换为 break @ forEach ,但Kotlin编译器说:

I tried replacing return@forEach with break@forEach but Kotlin compiler says :

推荐答案

这种方法怎么样?

rendered_words.reversed().firstOrNull { rw -> rw.y - the_top > 0 && rw.y - the_top < height }
?.let { new_top = it }
if(new_top != null) {
     smoothScrollTo(Math.min(text_y - height, new_top))
}

因为您似乎要尝试到达的是符合您条件的第一项,并且first/firstOrNull比forEach更好

because what you seem to try to get here is the first item that matches your condition, and the first/firstOrNull is better there than the forEach

这篇关于'返回'不会在Kotlin中脱颖而出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:09