Traversing through ranges using progression with a custom step value
Besides doing so for the Iterator
instances, progressions implementations for integral types, such as the Int
, Long
, and Char
types, also include the step
property. The step
value specifies the intervals between the subsequent elements of a range. By default, the step
value of a progression is equal to 1
. In this recipe, we are going to learn how to traverse a range of alphabet characters with a step
value equal to 2
. In the result, we want to have every second alphabet letter printed to the console.
Getting ready
The Kotlin standard library provides a convenient way of creating progression with a custom step
value. We can do so using an extension function for progressions of integral types called step()
. We can also benefit from the infix notation and declare a progression with a custom step
, as follows:
val progression: IntProgression = 0..1000 step 100
If we were to use progression
in the for
loop, it would iterate 10 times:
val progression: IntProgression = 0..1000 step 100 for (i in progression) { println(i) }
We could also achieve the same result by iterating with the while
loop, as follows:
var i = 0 while (i <= 1000) { println(i) i += 100 }
How to do it...
- Declare a range of the
Char
type using thedownTo()
function:
'z' downTo 'a'
- Convert the range to a progression with a custom
step
value using thestep()
function:
'z' downTo 'a' step 2
- Use the
forEach()
function to iterate through the elements of the progression and print each of them to the console:
('z' downTo 'a' step 2).forEach { character -> print(character) }
How it works...
In the result, we are going to get the following code printed to the console:
zxvtrpnljhfdb
In the beginning, we declared a range containing all the alphabet characters in decreasing order with the downTo()
function. Then, we transformed the range a the custom progression containing every second character with the step()
function. Finally, we are using the Iterable.forEach()
function to iterate through the next elements of the progression and print each of them to the console.
The step()
extension function is available for the IntProgression
, LongProgression
, and CharProgression
types. Under the hood, it creates a new instance of a progression copying the properties of the original one and setting up the new step
value.
See also
- Apart from iteration, range expressions are useful for defining flow control conditions. You can read more about this in the Using range expressions with flow control statementsrecipe.