`for` loop vs `forEach` lambda ?
# codingconventions
h
for
loop vs
forEach
lambda ?
g
Probably depends on the situation and style of programming.
forEach
is closer to FP and chained functions.
l
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
✔️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
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
(i in 0..lastIndex).forEach { foo++ }
But this is invalid Kotlin code. Valid version would be just:
Copy code
(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
yeah, i made a mistake.
my brain is tired today
🛏️ 1
g
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:
Copy code
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
Copy code
for (i in 0..lastIndex) foo++
k
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.