Kotlin Range Operator

Range Operator in Kotlin is a basic operator that is used to operate over a range. A range can be defined with a start value and an end value with and without inclusion.

The range operators can be used with for loops, if conditions or even in when operator. First, let to see a basic example of a range operator.

A basic range operator can be defined with .. having a lower range value to the left side and upper range value to the right side of ..

Lets try to understand the .. operator and its return type first.

rangeTo() function

.. is an operator overloading to rangeTo() function which is defined in kotlin.ranges package.

rangeTo() function is an extension function to the Template class where the Template class should implement the Comparable interface.
That means we can create a range to any primitive or non primitive data type which implements the Comparable interface.

ClosedRange

The rangeTo() function returns a ClosedRange interface object which has a start and an endInclusive variables and contains operator function which is used by the in operator and an isEmpty function.

CharRange, IntRange & LongRange

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-range-operator/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store