https://kotlinlang.org logo
Title
h

Hullaballoonatic

04/17/2019, 7:51 PM
for
loop vs
forEach
lambda ?
g

ghedeon

04/17/2019, 7:54 PM
Probably depends on the situation and style of programming.
forEach
is closer to FP and chained functions.
l

Luke

04/17/2019, 7:58 PM
I tend to use classic for loop only on ranges. I prefer
for(i in min..max)
than
(min..max).forEach
. Nevertheless, I think it’s up to your liking more than actual conventions
h

Hullaballoonatic

04/17/2019, 8:07 PM
✔️yeah, my preference is usually in readability. i also, maybe arbitrarily, never do a loop in a single line, but i'm willing to write lambda's in a single line.
for (i in 0..lastIndex) { foo++ }
-1
(i in 0..lastIndex).forEach { foo++ }
+1
idk
r

rakeeb

04/17/2019, 8:17 PM
you can’t
break
in a
forEach
(you could but you need to run it inside a
run
block). for me if you have a condition where you need to
break
out i’d go with
for
otherwise
forEach
g

gildor

04/18/2019, 1:08 AM
(i in 0..lastIndex).forEach { foo++ }
But this is invalid Kotlin code. Valid version would be just:
(0..lastIndex).forEach { foo++ }
I agree that it of course depend on case. For example if you have some
lastIndex
probably you have some collection (even some custom container, you can easily add extension for iterator), and in this case I don’t think that you need range for this, just
.forEach()
or
for (i in collection)
h

Hullaballoonatic

04/18/2019, 1:10 AM
yeah, i made a mistake.
my brain is tired today
🛏️ 1
g

gildor

04/18/2019, 1:13 AM
also if we talk about ranges, not about iteration on some collection, than for cases when I would like to just do something N times from0 I also often use repeat:
repeat(max) { }
But the same problem as with forEach, no
break
, so
for
or
while
loops are the only choice in many cases
i’m willing to write lambda’s in a single line
In case of
for
you don’t have lambda, so because of this you can omit curly braces, so +1 to
for
for (i in 0..lastIndex) foo++
k

kenkyee

10/29/2021, 2:20 PM
was looking at this a bit more and noticed https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt uses a mix of both. But also doesn't follow the guidelines mentioned here...i.e. no breaks needed in for loop but it's used.