When is .forEach {} preferred, vs java-style for l...
# getting-started
j
When is .forEach {} preferred, vs java-style for loop? It looks like both get support from the language, e.g. destructuring for loop values
f
forEach
uses an iterator, so if you care about that (you need your loop to be as performant as possible), then you should use the
for
loop, otherwise it's a matter of preference.
r
forEach
is inlined and uses a
for
loop, so it should only use an iterator when
for
uses an iterator.
forEach
is a tail function call, so it is often preferable for working with flows and pipelines. It does not support things like
break
and
continue
however, but from my experience those don't often play well with flows and pipelines anyway, as there would usually be some sort of
filter
or something earlier in the pipeline to account for it.
For just a simple "I need to loop over this collection and do stuff with the elements", generally prefer
for
. For anything more complex involving multiple steps,
forEach
makes a good step in the chain.
e
IMO: only use
forEach
when it is meaningfully more useful, e.g.
Copy code
foo["bar"]?.forEach { ... }
is more work to express with
for
. but otherwise use
for
it should only use an iterator when
@Ruckus not true; it always uses an iterator because that's resolved before inlining happens. e.g.
Copy code
for (i in 1..10) {} // compiler optimizes this to an increment
(1..10).forEach {} // constructs range object, iterator, and boxes
j
TIL, thanks all!
m
For the Kotlin coding conventions.
Prefer using higher-order functions (
filter
,
map
etc.) to loops. Exception: `forEach`(prefer using a regular
for
loop instead, unless the receiver of
forEach
is nullable or
forEach
is used as part of a longer call chain).
https://kotlinlang.org/docs/coding-conventions.html#loops
r
@ephemient Interesting, I thought I remembered that being included in the compiler intrinsics. That's good to know, thanks.