Ranges
Ranges
Range expressions are formed with rangeTo
functions that have the operator form ..
which is complemented by in and !in. Range is defined for any comparable type, but for integral primitive types it has an optimized implementation. Here are some examples of using ranges
if (i in 1..10) { // equivalent of 1 <= i && i <= 10 println(i) }
Integral type ranges (IntRange
, LongRange
, CharRange
) have an extra feature: they can be iterated over. The compiler takes care of converting this analogously to Java's indexed for-loop, without extra overhead.
for (i in 1..4) print(i) // prints "1234" for (i in 4..1) print(i) // prints nothing
What if you want to iterate over numbers in reverse order? It's simple. You can use the