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...