日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Kotlin 正確退出 foreach、foreachIndexed 循環(huán)函數(shù)

作者:匆忙擁擠repeat 更新時間: 2022-07-18 編程語言

文章目錄

  • 問題現(xiàn)象
  • 加標簽 label@ 嘗試解決
  • 解決方案,增加一個外部函數(shù)作用域

問題現(xiàn)象

(1..8).forEach {
	if (it % 2 == 0) {
		return@forEach
	}
	println("forEach: $it")
}

如上的 return 語句,并沒有 return 整個循環(huán)。
輸出:

forEach: 1
forEach: 3
forEach: 5
forEach: 7

相當于,僅是個類似 continue 的作用。
而在 foreach、foreachIndexed 循環(huán)函數(shù) 中,無法使用 continuebreak 關(guān)鍵字。


加標簽 label@ 嘗試解決

(1..8).forEach fe@{
    if (it % 2 == 0) {
        return@fe
    }
    println("forEach: $it")
}

加了標簽 fe@ 后,也并沒有改變輸出結(jié)果。這里的加標簽,只是對默認的函數(shù)名 forEach@ 的重命名


解決方案,增加一個外部函數(shù)作用域

增加一個外部函數(shù)作用域:

(1..8).also { range ->
    range.forEach fe@{
        if (it % 2 == 0) {
            return@also
        }
        println("forEach: $it")
    }
}

return@also 退出了整個 also {}
輸出:

forEach: 1

可以對 also { } 取別名標簽。 eg. (1…8).also oneAlso@ { … }

當然選擇其它的標準函數(shù) (also、let、run、apply、with) 作外部函數(shù),都可以。

with (1..8) {
   this.forEach fe@{
       if (it % 2 == 0) {
           return@with
       }
       println("forEach: $it")
   }
}

原文鏈接:https://blog.csdn.net/jjwwmlp456/article/details/125797242

欄目分類
最近更新