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.
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