That was confusing… ``` listOf(1,2,3,4,5).forE...
# announcements
a
That was confusing…
Copy code
listOf(1,2,3,4,5).forEach {
        if (it > 3) //actually evaluates 5 times
        	return@forEach
    }
Any way to stop
forEach
without using the label?
s
Convert to for-loop and
break
d
if you need the first item which meets a condition, why not use
firstOrNull
?
☝️ 1
or
filter
if you need all of them
a
In the real code it’s a bit more complex
Copy code
listOf(errorResolutions).forEach{
  if (it.resolvesError()) {
     return@foreEach
  }
}
So the idea was to stop checking if error was resolved by one of the resolutions
g
maybe
.takeWhile {}
or I'm pretty sure
.any{}
will stop as soon as one is found
s
Note that the lambda in your initial example is actually run 5 times. For breaking out of the foreach entirely you need something like the last sample here: https://kotlinlang.org/docs/reference/returns.html
Which is ugly as f... Personally I would prefer the loop + break
a
I actually like the
takeWhile {}
suggestion I think it will work perfectly in this case
thanks
🙂 1
g
No, you just print it 3 times, but block will be called 5 times. Just move println above
return
to check it
i
I see what you mean. I think this is the issue to vote for https://youtrack.jetbrains.com/issue/KT-1436
r
takeWhile
is best choice