LoginSignup
25
15

More than 3 years have passed since last update.

KotlinでforEachから抜け出す

Last updated at Posted at 2018-07-24

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

なんでやねん :persevere:

抜け出せるコード

こうやるみたいです。

run loop@ {
    (1..10).forEach {
        println("_/_/ $it")
        if (it == 5) {
            return@loop
        }
    }
}

実行すると...

_/_/ 1
_/_/ 2
_/_/ 3
_/_/ 4
_/_/ 5

おっけーです。

return@forEachbreakではなくてcontinueらしいですね。

こういうのは公式リファレンスに書いておいて欲しい :droplet:

こちらを参考にしました

'return' doesn't jump out of forEach in Kotlin
https://stackoverflow.com/questions/48056994/return-doesnt-jump-out-of-foreach-in-kotlin

25
15
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
15