kotlin跳出for迴圈
阿新 • • 發佈:2020-12-24
技術標籤:kotlin
效果一:陣列的forEach中直接retrun
private fun test0() {
val arr = intArrayOf(1,2,3,4,5,6,7)
arr.forEach {
if (it == 4) return
Log.d(TAG, "value:$it")
}
Log.d(TAG, "this is End")
}
列印結果:
可以看到程式程式在遍歷到4的時候就退出了方法,而且this is End
我若果只想在陣列遍歷到4的時候跳出forEach,forEeach後面的語句還繼續執行,實現類似java中的continue,那麼應該怎麼做呢
效果二:continue
private fun test() { val arr = intArrayOf(1, 2, 3, 4, 5, 6, 7) arr.forEach [email protected]{ if (it == 4) [email protected] Log.d(TAG, "value:$it") } Log.d(TAG, "this is End") }
列印結果:
可以看到在遍歷到4的時候直接跳出了此次迴圈,假設當遍歷到4的時候,想要直接跳出遍歷迴圈,實現類似java中的break的作用,那麼應該怎麼做呢
效果三:break
private fun test2() { val arr = intArrayOf(1, 2, 3, 4, 5, 6, 7) run [email protected]{ arr.forEach [email protected]{ if (it == 4) [email protected] Log.d(TAG, "value:$it") } Log.d(TAG, "this is breaking") } Log.d(TAG, "this is End") }
列印結果:
可以看到的是在資料遍歷到4的時候,直接就跳出了迴圈體,繼續執行下面的程式碼,實現了在kotlin的forEach中類似java的break的效果。