Jonathan Ellis
06/03/2022, 5:28 PMFrancesc
06/03/2022, 5:38 PMforEach 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.Ruckus
06/03/2022, 5:43 PMforEach 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.Ruckus
06/03/2022, 5:45 PMfor. For anything more complex involving multiple steps, forEach makes a good step in the chain.ephemient
06/03/2022, 5:45 PMforEach when it is meaningfully more useful, e.g.
foo["bar"]?.forEach { ... }
is more work to express with for. but otherwise use forephemient
06/03/2022, 5:48 PMit should only use an iterator when
@Ruckus not true; it always uses an iterator because that's resolved before inlining happens. e.g.
for (i in 1..10) {} // compiler optimizes this to an increment
(1..10).forEach {} // constructs range object, iterator, and boxesJonathan Ellis
06/03/2022, 6:03 PMmkrussel
06/03/2022, 6:11 PMPrefer using higher-order functions (https://kotlinlang.org/docs/coding-conventions.html#loops,filteretc.) to loops. Exception: `forEach`(prefer using a regularmaploop instead, unless the receiver offoris nullable orforEachis used as part of a longer call chain).forEach
Ruckus
06/03/2022, 6:29 PM