Kotlin provides a unique type for a range of values. A range has a start and an end value.
To create a range you can use the rangeTo() function.
This code defines a range variable myRange containing values from 1 to 10 inclusive.
Ranges in Kotlin are closed, this mean that the start value and the end value are included in the range.
To create a decressing range, use the downTo() function.
myRange contains the values: 8, 7, 6, 5, 3, 2
The .. operator
Another way to define a range is using the .. (double dot) operator.
The in operator allows to verify if a value belongs to a range.
Output: 5 is in the range
Similarly, !in can be used to check if a number does not belong to a range.
It is also possible to iterate over numbers with an arbitrary step (not necessarily 1). This is done via the step function.
To iterate a number range which does not include its end element, use the until function.
In this example you can see that the first element is in the range, but the last one isn’t.
Cool Trick 🙂
Ranges can also hold upper and lover case alphabets.
//a, b, c, d
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂