Kotlin forEach退货标签不为';行不通

Kotlin forEach退货标签不为';行不通,kotlin,Kotlin,写的是我们可以用label中断forEach 我在我的android应用程序中尝试了它,但失败了,接下来我在官方页面上用演示代码进行了尝试,但也没有成功 有人能解释一下为什么这个代码不起作用以及如何修复它吗 fun foo() { listOf(1, 2, 3, 4, 5).forEach lit@{ if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop

写的是我们可以用label中断forEach

我在我的android应用程序中尝试了它,但失败了,接下来我在官方页面上用演示代码进行了尝试,但也没有成功

有人能解释一下为什么这个代码不起作用以及如何修复它吗

fun foo() {
listOf(1, 2, 3, 4, 5).forEach lit@{
    if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
    print(it)
}
print(" done with explicit label")
}

错误结果:

1245 done with explicit label
编辑: 只有在阅读了答案之后,我才意识到答案就在那一页上,但只有在最后:

Note that the use of local returns in previous three examples is similar to the use of continue in regular loops
所以,我确信早些时候他们谈论的是
break
,而不是
continue

最好将此注释放在页面上的示例之前,以免产生误导,但无论如何,最好的答案是使用
takeWhile
是,这是预期的结果。使用带有标签的return(如
forEach
中的标签)与Java中的
continue
具有相同的行为

我猜您希望它在Java中表现得像
break
,在这种情况下,您可以将
forEach

结果将是

12 done with takeWhile

是的,这是预期的结果。使用带有标签的return(如
forEach
中的标签)与Java中的
continue
具有相同的行为

我猜您希望它在Java中表现得像
break
,在这种情况下,您可以将
forEach

结果将是

12 done with takeWhile

是的,这是预期的行为。链接页面也有一个解决方案,为您寻找

fun main() {
 run loop@{
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return@loop // non-local return from the lambda passed to run
        print(it)
    }
 }
 print(" done with nested loop")
}

是的,这是预期的行为。链接页面也有一个解决方案,为您寻找

fun main() {
 run loop@{
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return@loop // non-local return from the lambda passed to run
        print(it)
    }
 }
 print(" done with nested loop")
}

你链接的这篇文章解释了为什么这实际上是预期的结果,它还包括我认为你试图实现的行为的解决方案。每次我看到这些标签问题,我更确信它们是个坏主意,最好是避开它们。@AdamMillerchip他们需要赶快添加break并继续内联lambdas。他们说他们几年前就计划这么做了,但解决方法很糟糕。你链接的文章解释了为什么这实际上是预期的结果,还包括我认为你试图实现的行为的解决方案。每次我看到这些标签问题,我更确信它们是个坏主意,最好是避开它们。@AdamMillerchip他们需要赶快添加break并继续内联lambdas。他们说他们几年前就计划这么做了,但解决办法很难看。这也是一个很好的答案,因为它显示了如何在相同的
forEach中使用
break
continue
,这也是一个很好的答案,因为它显示了如何在相同的
forEach
中使用
break
continue