After Learning Kotlin – Part 1 and Learning Kotlin – Part 2 we will now dive into the ranges.
One nice little feature is the .. syntax: you can generate an IntRange object just by specifying the start and the end element:
val oneTo10 = 1..10
You can even use values for the start and end data
val one = 1 val ten = 10 val oneToTen = one..ten
Compared to the range function in Python the last element is included, which is less error prone.
You can use the rangeTo function as well:
val twoTo20 = 2.rangeTo(20)
It works as well with characters
val alpha = "A".."Z"
The syntax for a reversed range looks like this
val tenTo1 = 10.downTo(1)
You can get a ‘subset’ of a range with the step function
val rng = oneTo10.step(3)
You can reverse an existing range
tenTo1.reversed()
So, there are many possibilities to make ranges in Kotlin! Yeah!