The label does not denote a loop in forEach

这个是在kotlin中遍历集合时,使用标签的过程中,可能会遇到的小错误。

提示的字面上的信息,就是在forEach中这个标签不能表示为loop(也就是循环),错误事例如下:

list.forEach loop@{
      if (it == "外面还很黑") {
           continue @loop
       }
   }
复制代码

这里使用continue,和break都会报错。使用return就会正常了,让我们看看源码:

/**
 * Performs the given [action] on each element.
 */
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

复制代码

很明显forEach是一个fun,并不是一个loop

那么相对应的,在for 循环中使用return 也同样会报错。错误代码如下:

loop@ for (i in 0..4)  
               for (j in 5..9) {
                   if (j == 8) {
                       return@loop
                  }
           }
复制代码

这个时候编译器会给一个warn:Target label does not denote a function

改正:我们可以使用continue,或者break,看你的实际情况来定

官方讲解

Returns and Jumps

Kotlin has three structural jump expressions:

  • return. By default returns from the nearest enclosing function or anonymous function.
  • break. Terminates the nearest enclosing loop.
  • continue. Proceeds to the next step of the nearest enclosing loop.

我是翻译二把刀,你们自己看吧 还想了解一下kotlin中的循环的,请走这边blog.csdn.net/u010844304/…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值