2020年7月6日追記
現在では、break
および continue
が使えるようになっている模様です。
https://kotlinlang.org/docs/reference/returns.html
forEach
ループから脱出できずにキレそうになったのでメモを残しておきます。
抜け出せないコード
コレを実行すると...
(1..10).forEach {
println("_/_/ $it")
if (it == 5) {
return@forEach
}
}
こうなります。
_/_/ 1
_/_/ 2
_/_/ 3
_/_/ 4
_/_/ 5
_/_/ 6
_/_/ 7
_/_/ 8
_/_/ 9
_/_/ 10
なんでやねん
抜け出せるコード
こうやるみたいです。
run loop@ {
(1..10).forEach {
println("_/_/ $it")
if (it == 5) {
return@loop
}
}
}
実行すると...
_/_/ 1
_/_/ 2
_/_/ 3
_/_/ 4
_/_/ 5
おっけーです。
return@forEach
はbreak
ではなくてcontinue
らしいですね。
こういうのは公式リファレンスに書いておいて欲しい
こちらを参考にしました
'return' doesn't jump out of forEach in Kotlin
https://stackoverflow.com/questions/48056994/return-doesnt-jump-out-of-foreach-in-kotlin