Loops in Kotlin

There’s a common way in Java to do loops. One of the most well-known ways to iterate on a range is to use the traditional for loop. A more modern approach would be something like using a Java 8 IntStream. Examples of either can be seen below:

// Traditional for loop
for (int i = 0; i < 100; i++) {
    System.out.println(i);            
}

// IntStream
IntStream.range(0, 100).forEach(System.out::println);

A Kotlin Approach

Kotlin provides its own way of looping on ranges. Inspired by the Kotlin Under the Hood: Understand the Internals (Google I/O’19) video (which is a really good video btw, I’d recommend watching it if you haven’t), I wanted to list a few ways of looping it Kotlin.

Kotlin for loop

In Kotlin the for loop is used to iterate through a diversity of types to loop over, such as collections, ranges and maps. Any class which provides an iterator can be looped over. As such, the syntax of for loop in Kotlin is:

for (element in collection) {
    // process element
}

As mentioned, in Kotlin it’s possible to use a for loop on a range. This is arguably the simplest way of doing a loop:

// Simple for loop on range
for(i in 0..100) { }

When using ranges, it’s also possible to use the step option, so every loop increments with the value as indicated by the step:

// Simple for loop on range with step
for(i in 0..100 step 5) { }

Kotlin loop using until

Another way of looping is to use the until function. In this way, you can loop over a range which does not include its last element. So, a loop of 0 until 10 will stop at element 9:

// Using non-inclusive range 
for(i in 0 until 100) { }

Kotlin loop using repeat

Kotlin also provides a built-in repeat function, which takes a lambda function to iterate over. In this way, you don’t use a range.

// Built-in Kotlin function
 repeat(100) { }

Kotlin loop using a forEach

While the Kotlin forEach on a range looks pretty similar to the other options, under the hood things work a bit different, which can be seen in the linked video at the 25-minute mark. In a nutshell, the Kotlin compiler creates an Iterable object and IntRange object, and then the iteration will take place. This shouldn’t matter much in terms of performance, but it’s something to be aware of in performance critical code.

// ForEach loop
(0..100).forEach

Conclusion

I hope the above gives a bit of an insight into different ways of looping in Kotlin. In case I missed one, please let me know in the comments below!

Older Post
Newer Post

Leave a Reply

Your email address will not be published. Required fields are marked *