網(wǎng)站首頁 編程語言 正文
文章目錄
- 問題現(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ù) 中,無法使用 continue
和 break
關(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
相關(guān)推薦
- 2022-10-14 VSCode連接實驗室服務(wù)器Xshell,Xftp向服務(wù)器傳輸文件的方法(win10)_Linux
- 2022-02-17 docker容器內(nèi)的數(shù)據(jù)存放在哪里
- 2022-11-28 Git基礎(chǔ)學(xué)習(xí)之tag標簽操作詳解_相關(guān)技巧
- 2023-03-28 通知監(jiān)控NotificationListenerService?onNotificationPost
- 2022-11-18 Nginx中rewrite(地址重定向)的深入剖析_nginx
- 2023-01-01 解決React報錯Property?'X'?does?not?exist?on?type?'HTML
- 2022-10-20 kotlin淺析when與循環(huán)的使用_Android
- 2022-07-09 springboot 視圖集成
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支