Kotlin supports the concept of ranges, which represent sequences of comparable types. To create a range, we can use the rangeTo methods that are implemented in classes, such as Int, in the following way:
public operator fun rangeTo(other: Byte): LongRange = LongRange(this, other)
public operator fun rangeTo(other: Short): LongRange = LongRange(this, other)
public operator fun rangeTo(other: Int): LongRange = LongRange(this, other)
public operator fun rangeTo(other: Long): LongRange = LongRange(this, other)
So, we have two options for creating a range, as follows:
- Using the rangeTo method. This may look as follows—1.rangeTo(100).
- Using the .. operator. This may look as follows—1..100.
Ranges are extremely useful when we work with loops:
for (i in 0..100) {
// .....
}
The 0..100 range is equal to the 1 <= i && i <= 100 statement.
If you want to exclude the last value, you can use the until function, in the following way:
0 until 100
We can also use the step function, as follows:
1..100 step 2
The preceding snippet represents a range like the following:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, ... 99]
It's worth mentioning that ranges support a lot of until functions, such as filter or map:
(0..100)
.filter { it > 50 }
.map { it * 2 }