![]() ![]() It is the operator form of rangeTo () function. ![]() It will create a range from the start to end including both the values of start and end. I hope the above gives a bit of an insight into different ways of looping in Kotlin. There are three ways for creating Range in Kotlin Using (.) operator Using rangeTo () function Using downTo () function (.) operator It is the simplest way to work with range. 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. Kotlin provides a set of built-in types that represent numbers. 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. In Kotlin the for loop is used to iterate through a diversity of types to loop over, such as collections, ranges and maps. 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 Examples of either can be seen below: // Traditional for loop A more modern approach would be something like using a Java 8 IntStream. One of the most well-known ways to iterate on a range is to use the traditional for loop. Kotlin - Ranges Ranges Range expressions are formed with rangeTo functions that have the operator form. There’s a common way in Java to do loops. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |