Kotlin 中的 'break' 和 'continue'
在 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 {
// break this iteration when
// the condition is satisfied and
// jump back to the calling function
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 时返回到调用函数,即 main()。
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@{
// break this iteration when the condition
// is satisfied and continue with the flow
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP