Ranges and progressions
Ranges and progressions define sequences of values in Kotlin, supporting range operators, iteration, custom step values, and arithmetic progressions.
Ranges
Kotlin lets you easily create ranges of values using the .rangeTo()
and .rangeUntil()
functions from the kotlin.ranges
package.
A range represents an ordered set of values with a defined start and end. By default, it increments by 1 at each step. For example, 1..4
represents the numbers 1, 2, 3, and 4.
To create:
a closed-ended range, call the
.rangeTo()
function with the..
operator. This includes both the start and end values.an open-ended range, call the
.rangeUntil()
function with the..<
operator. This includes the start value but excludes the end value.
For example:
Ranges are particularly useful for iterating over for
loops:
To iterate numbers in reverse order, use the downTo
function instead of ..
.
You can also iterate over numbers with a custom step using the step()
function, instead of the default increment of 1:
Progression
The ranges of integral types, such as Int
, Long
, and Char
, can be treated as arithmetic progressions. In Kotlin, these progressions are defined by special types: IntProgression
, LongProgression
, and CharProgression
.
Progressions have three essential properties: the first
element, the last
element, and a non-zero step
. The first element is first
, subsequent elements are the previous element plus a step
. Iteration over a progression with a positive step is equivalent to an indexed for
loop in Java/JavaScript.
When you create a progression implicitly by iterating a range, this progression's first
and last
elements are the range's endpoints, and the step
is 1.
To define a custom progression step, use the step
function on a range.
The last
element of the progression is calculated this way:
For a positive step: the maximum value not greater than the end value such that
(last - first) % step == 0
.For a negative step: the minimum value not less than the end value such that
(last - first) % step == 0
.
Thus, the last
element is not always the same as the specified end value.
Progressions implement Iterable<N>
, where N
is Int
, Long
, or Char
respectively, so you can use them in various collection functions like map
, filter
, and other.