https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jonathan Ellis

06/03/2022, 5:28 PM
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

Francesc

06/03/2022, 5:38 PM
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

Ruckus

06/03/2022, 5:43 PM
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

ephemient

06/03/2022, 5:45 PM
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

Jonathan Ellis

06/03/2022, 6:03 PM
TIL, thanks all!
m

mkrussel

06/03/2022, 6:11 PM
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

Ruckus

06/03/2022, 6:29 PM
@ephemient Interesting, I thought I remembered that being included in the compiler intrinsics. That's good to know, thanks.
21 Views