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
廣告