In today’s article I want to continue with Kotlin basics and I will look into Ranges, Arrays and Collections. We know that Kotlin is a multi-paradigm language but in this basics article I am not going to focus in advanced functional features, I am rather going to explain the constructs using a simple imperative style in the examples. In future articles I will dive deeper into functional Kotlin.
Iterating ranges
In Kotlin there are specialised classes that represent ranges of values. This is very convenient and simplifies lot of tasks. Let’s have a look at some range examples.
- A constant with an example range of integers from 1 to 100
- A constant with an example range of integers from 1 to 100, with the type inferred
- A for loop that iterates the numbers range
- A for loop that iterates the range that is declared within the loop rather than externally
- A loop that iterates backwards from 50 down to 3
- A loop that iterates backwards from 50 down to 3 but uses the infix notation(no brackets)
- A loop that iterates from 1 until 10. The until keyword excludes the last element. This will print only 1,2,3,4,5,6,7,8,9
- A loop that uses a step to jump some of the values. The numbers printed will be 1,3,5,7,9
- A loop with a filter predicate will only iterate the values within the range that match what is defined in the predicate.
This examples so far were for IntRange, but Kotlin also supports other types of ranges. For example characters.
Also ranges can support Strings or even more complex types but the implementation of the iterator() will have to be provided by the developer because the class CloseRange does not implement it by default.
In the above example we can use the contains function but if we were to try to iterate we would get a compilation error.
This is because CloseRange does not implement iterator(). The developer will have to create an extension function to implement the way desired for the iteration. This is just an example that will delegate to a CharRange and it will allow to iterate Strings.
Array and Lists iteration
To create arrays in Kotlin the arrayOf function is used. There’s no need to use import statements to call it since it belongs to the kotlin package.
If instead of an array we wanted a list, then we use the listOf function.
If we want an index when have a couple of options.
The first loop uses the indices attribute to return the order of the element which is being iterated. In order to get the index and the value, a further call to get() providing the index is needed.
A nicer approach is also possible as shown in the second loop. The destructing feature is used to extract the values returned from the withIndex() function to get both index and the value at once. In this article I just wanted to show the iteration and usages basics of arrays and ranges. In future posts I will talk a bit in depth about Kotlin collections.