

I hope the above gives a bit of an insight into different ways of looping in Kotlin. This shouldn’t matter much in terms of performance, but it’s something to be aware of in performance critical code. In a nutshell, the Kotlin compiler creates an Iterable object and IntRange object, and then the iteration will take place. 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. As such, the syntax of for loop in Kotlin is: for (element in collection) Kotlin loop using a forEach Any class which provides an iterator can be looped over. Inside the loop, you add i to the sum variable it runs 10 times to.

In Kotlin the for loop is used to iterate through a diversity of types to loop over, such as collections, ranges and maps. Note: If youd used a half-open range, the last iteration would see i equal to count - 1. 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 provides its own way of looping on ranges. IntStream.range(0, 100).forEach(System.out::println) A Kotlin Approach A range of dates can be represented by a DateRange, which is also a progression, allowing you to iterate over each day in the range. Examples of either can be seen below: // Traditional for loop array (range (0,5)) And I want to transform it two a 2-dimensional. A more modern approach would be something like using a Java 8 IntStream. Here we are going to discuss three ways using for loop, enhanced for loop. One of the most well-known ways to iterate on a range is to use the traditional for loop. There’s a common way in Java to do loops.
