Kotlin Range Operator

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-range-operator/ and reposted on Medium on 12th April 2022.
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")
}
}

rangeTo() function

/**
* 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

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/

--

--

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