Kotlin: For-loop vs ForEach

--

With Kotlin, we can write loop for(i in a..b){} and we could also do (a..b).forEach{}. Which should we use?

Well, instead of arbitrary decide, or just use the seemingly more glamorous functional style, let’s do some pragmatic comparison.

Simple Loop

// For loop
for (i in 0..10) { println(i) }
// ForEach
(0..10).forEach { println(it) }

From the above, both looks similar, except for normal for has an extra i variable there.

Collection

// For loop
val list = listOf(1, 2, 3).filter( it == 2 )
for (i in list) { println(i) }
// ForEach
listOf(1, 2, 3).filter( it == 2 ).forEach { println(it) }

If the data source is an iterable collection, forEach would be better, as it could be chained together.

Continue

// For loop
for (i in 0 until 10 step 3) {
if (i == 6) continue
println(i)
}
// ForEach
(i in 0 until 10 step 3).forEach {
if (it == 6) return@forEach
println(it)
}

If you need continue, the forEach has the ugly looking return@forEach. For-loop is better here.

Break

// For loop
for (i in 0 until 10 step 3) {…

--

--