From `for` to `onEach`: Guide to choosing the righ...
# feed
c
🚫 1
👎 1
💜 1
c
```for (i in 0..10) {
println(i)
}```
```(1..10).forEach {
println(i)
}```
IMO, the first one is much easier to read, the second is just noise on top of it. But also, in this situation, none of these are idiomatic, it would be better to use
Copy code
repeat(10) {
    println(it)
}
Also, your article is named "stop using the wrong loop", but all it does is list all the different kinds of loops.
The
while
and
do … while
examples contradict your text: in both situations, you know exactly how many loops are going to be executed. They should be written with
Copy code
for (x in 5 downTo 1) {
    println(x)
}
c
Thanks mate for feedback, aim was to help understand when each one is most appropriate to use by providing an overview of possible options available. Definitely you can loop however you like, I like to be explicit about my intentions while looping and classification in this article helps me alot. However, I appreciate your point.
m
JetBrains style guide has guidance on when to use the for loop and the forEach function.
👍 1