Kotlin 正确退出 foreach、foreachIndexed 循环函数

问题现象

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

如上的 return 语句,并没有 return 整个循环。
输出:

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

相当于,仅是个类似 continue 的作用。
而在 foreach、foreachIndexed 循环函数 中,无法使用 continuebreak 关键字。


加标签 label@ 尝试解决

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

加了标签 fe@ 后,也并没有改变输出结果。这里的加标签,只是对默认的函数名 forEach@ 的重命名


解决方案,增加一个外部函数作用域

增加一个外部函数作用域:

(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@ { … }

当然选择其它的标准函数 (also、let、run、apply、with) 作外部函数,都可以。

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

猜你喜欢

转载自blog.csdn.net/jjwwmlp456/article/details/125797242