Journal for Developers

Pondering over Kotlin Ranges

Kotlin Ranges
0 61
2 min read

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);
}

[quads ad=1]

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

Have you noticed that the second statement prints out nothing. That’s because IntRange is defined by its minimum start and its maximum endInclusive values. In other words, when endInclusive < start, the range is empty.

You can use downTo() function which is defined in the standard library to iterate the Range in reverser order.

[quads ad=2]

Alternatively, you can also use the progression. A progression can be any arithmetic sequence, so it can go up or down. Here are two ways to make a decrementing progression:

//Using downTo() function
for (i in 4 downTo 1) print(i) // prints "4321"

//Using reversed() function
(1..3).reversed().forEach(System.out::print)

Can Ranges in Kotlin do the same magic as other language iterator of stepping the numbers more than the default value of 1. Well, the answer is YES. Here is the implementation for your quick reference to step the range for the value greater than 1.

for (i in 1..4 step 2) print(i) // prints "13"

for (i in 4 downTo 1 step 2) print(i) // prints "42"

Another great point in Ranges is not to include the last element in the Range.

for (i in 1 until 10) { // i in [1, 10), 10 is excluded
     println(i)
}

Well this is just the glimpse of the Ranges in Kotlin, in the next journal entry we will try to explore how internally this works.

[quads ad=3]

Subscribe to our Journal

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!