Kotlin Ranges Creation Options

Kotlin Ranges Creation Options

A Kotlin range is a series of consecutive items between defined lower and upper limits. The range definition states: it is defined by its two endpoint values which are both included in the range.
However, you can define ranges without upper limit included. This post is about options how to create Kotlin ranges.

 

There are 4 main ways to create ranges in Kotlin:

  • double dot operator, e.g.
    • 'a'..'d'
  • until function, e.g.
    • 'a' until 'd'
  • rangeTo function, e.g.
    • 'a'.rangeTo('d')
  • downTo function, e.g.
    • 'd'.downTo('a')

 

While the double dot operator creates a range including the lower and upper limit,

the until function creates a range including the lower and excluding the upper limit.

('a'..'d').joinToString(",")        // creates "a,b,c,d"
('a' until 'd').joinToString(",")   // creates "a,b,c"

It’s recommended to use the until function over an open range (see loops on ranges):

for (i in 0..n - 1) { ... }  // bad
for (i in 0 until n) { ... }  // good

 

The functions rangeTo and downTo are complementary with respect to the ranges produced:

('a'.rangeTo('d')).joinToString(",")             // creates "a,b,c,d"
('d'.downTo('a')).joinToString(",")              // creates "d,c,b,a"
('d'.downTo('a')).reversed().joinToString(",")   // creates "a,b,c,d"

A range created with downTo and reversed is equal to the equivalent range created with rangeTo.

You can find the sample code in gh.com/lotharschulz/kotlin-ranges.

Conclusion

There are several options to create ranges in Kotlin that produce slightly different results.

Further reading

There are more details to ranges that are not covered in this post:

Lothar Schulz

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.