The label does not denote a loop in forEach

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010844304/article/details/86345405

这个是在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中的循环的,请走这边https://blog.csdn.net/u010844304/article/details/86295639

猜你喜欢

转载自blog.csdn.net/u010844304/article/details/86345405