Kotlin forEach 中的"break"和"continue"

kotlin mobile developmentapps/applications更新于 2026/1/5 1:52:17

在 Kotlin 中,我们有三种类型的结构跳转表达式:"break"、"return"和"continue"。在本文中,我们将了解 break 和 continue 在 Kotlin 中的工作原理。

  • Break - 这是一个关键字,用于在遍历集合时,一旦满足给定条件,就终止迭代。

  • Continue - 此关键字用于在满足条件后继续迭代。

在 Kotlin 中,我们无法在 forEach 循环中显式使用 break 和 continue 语句,但我们可以模拟相同的操作。在这个例子中,我们将看到如何做到这一点。

示例:在标签 :: 处直接返回给调用者

在这个例子中,我们将看到如何在当前循环中停止执行,并将编译器执行移回调用者函数。这相当于break。

fun main(args: Array<String>) {
   myFun()
   println("Welcome to TutorialsPoint")
}

fun myFun() {
   listOf(1, 2, 3, 4, 5).forEach {

      // 当满足以下条件时中断本次迭代:
      // 条件满足且
      // 跳转回调用函数
      if (it == 3) return
      println(it)
   }
    println("This line won't be executed." + "It will be directly jump out" + "to the calling function, i.e., main()")
}

输出

一旦我们执行上述代码,它将终止函数 myFun() 的执行,并在迭代索引的值达到 3 时返回调用函数,即 ma​​in()。

1
2
Welcome to TutorialsPoint

示例:在标签处返回 :: 本地返回给调用者

在上面的例子中,如果我们只想在特定条件下停止循环执行,那么我们可以实现本地返回给调用者。在本例中,我们将看到如何实现相同的功能。这相当于"continue"。

fun main(args: Array<String>) {
   myFun()
   println("Welcome to TutorialsPoint")
}

fun myFun() {
   listOf(1, 2, 3, 4, 5).forEach ca@{
      // 当条件满足时中断本次迭代
      // 并继续执行流程
      if (it == 3) return@ca
      println(it)
   }
   println("This line will be executed
" + "because we are locally returing
" + "the execution to the forEach block again") }

输出

它将生成以下输出

1
2
4
5
This line will be executed because we are locally returning the execution to the forEach block again
Welcome to TutorialsPoint

相关文章