Looping in Kotlin

Ever wonder how many ways you could write a looping code in Kotlin?

Classic

1. Dynamic condition start

while(dynamicCondition()) {
doSomething()
}

In this loop, it would terminate on dynamic condition.

2. Dynamic condition later

If you could only determine is after your operation, use do-while

do {
doSomething()
} while (dynamicCondition())

3. Simple for-loop

for (i in start..end) {
doSomething(i)
}

In this loop, you’ll know the start and the end. This is not as classic since it is using some IntRange object type i.e. ...

It has the nice step function as well

for (i in start..end step interval) {
doSomething(i)
}

4. Reverse looping

for (i in end downTo start) {
doSomething(i)
}

The downTo enable a reverse looping. It could also be

for (i in end..start) {
doSomething(i)
}

Collection based

5. Array index friendly for-loop

for (i in 0 until size) {
doSomething(i)
}

In the old days, we would have to do something like 0..size-1, now the until help do the trick.

6. Collection looping

for (i in listOf(1, 2, 4, 5)) {
doSomething(i)
}

If you really want to iterate through your collection, better do it directly, without using the index. You could do on array as well etc.

7. Collection index looping

for (i in listOf(1, 2, 4, 5).indices) {
doSomething(i)
}

Somehow if you need to get through the index instead, indices would be handy

8. Index and value looping

for ((index, value) in listOf(1, 2, 4, 5).withIndex()) {
doSomethingWith(index, value)
}

9. String looping

for (i in "SomeText") {
doSomething(i
}

What bout String? It’s an array of Character :)

Functional

10. Just a function

repeat(x) {
doSomething(it)
}

If you’t need to loop through x times, repeat will do the work. It actually start from 0 will x-1.

11. Semi functional

(start..end).forEach {
doSomething(it)
}

I call this semi-functional, as it helps to iterate through the value, but doesn’t further return something or itself. I will need to be the last part of the chain.

You could do it for collection as well

collection.forEach {
doSomething(it)
}

12. Semi functional reverse

(start..end).reversed().forEach {
doSomething(it)
}

You could reverse the sequence easily with the reversed() operation.

13. Fully functional

(start..end).map {
doSomething(it)
}

This approach would enable one other than doSomething(it), it also could use the result of doSomething(it) to have further functional operation.


I’m sure you’ll be able to find more similar to the above. If you have something that is most interesting that is not covered above, feel free to share with with me.

I hope this post is helpful to you. You could check out my other interesting topics here.

Follow me on medium, Twitter or Facebook for little tips and learning on Android, Kotlin etc related topics. ~Elye~