Ch8n
05/30/2024, 7:04 AMfor to `onEach`: Guide to choosing the right loop!
read 👉 https://chetan-garg36.medium.com/stop-using-the-wrong-loop-from-for-to-oneach-ultimate-guide-to-kotlin-loops-42dd25d6f3b3CLOVIS
05/30/2024, 8:09 AM```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
repeat(10) {
println(it)
}CLOVIS
05/30/2024, 8:10 AMCLOVIS
05/30/2024, 8:14 AMwhile 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
for (x in 5 downTo 1) {
println(x)
}Ch8n
05/30/2024, 8:20 AMMichael Krussel
05/30/2024, 11:44 AM