Kotlin Range Operator

Suneet Agrawal
2 min readApr 12, 2022

--

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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-range-operator/ and reposted on Medium on 12th April 2022.

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 ..

val x = 4for (item in 1..10){
println(item)
}
if ((1..10).contains(x)){
println("X is in range")
}
when (x){
in 1..10 -> {
println("X is in range")
}
}

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.

/**
* Creates a range from this [Comparable] value to the specified [that] value.
*
* This value needs to be smaller than or equal to [that] value, otherwise the returned range will be empty.
* @sample samples.ranges.Ranges.rangeFromComparable
*/
public operator fun <T : Comparable<T>> T.rangeTo(that: T): ClosedRange<T> = ComparableRange(this, that)

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.

package kotlin.ranges/**
* Represents a range of values (for example, numbers or characters).
*/
public interface ClosedRange<T: Comparable<T>> {
/**
* The minimum value in the range.
*/
public val start: T
/**
* The maximum value in the range (inclusive).
*/
public val endInclusive: T
/**
* Checks whether the specified [value] belongs to the range.
*/
public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive
/**
* Checks whether the range is empty.
*
* The range is empty if its start value is greater than the end value.
*/
public fun isEmpty(): Boolean = start > endInclusive
}

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.

--

--