|
1 | 1 | [//]: # (title: Ranges and progressions)
|
2 | 2 |
|
| 3 | +Ranges and progressions define sequences of values in Kotlin, supporting range operators, iteration, custom step values, and arithmetic progressions. |
| 4 | + |
| 5 | +## Ranges |
| 6 | + |
3 | 7 | Kotlin lets you easily create ranges of values using the [`.rangeTo()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/range-to.html)
|
4 | 8 | and [`.rangeUntil()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/range-until.html) functions from the
|
5 | 9 | `kotlin.ranges` package.
|
6 | 10 |
|
| 11 | +A range represents an ordered set of values with a defined start and end. By default, it increments by 1 at each step. |
| 12 | +For example, `1..4` represents the numbers 1, 2, 3, and 4. |
| 13 | + |
7 | 14 | To create:
|
8 |
| -* a closed-ended range, call the `.rangeTo()` function with the `..` operator. |
9 |
| -* an open-ended range, call the `.rangeUntil()` function with the `..<` operator. |
| 15 | + |
| 16 | +* a closed-ended range, call the `.rangeTo()` function with the `..` operator. This includes both the start and end values. |
| 17 | +* an open-ended range, call the `.rangeUntil()` function with the `..<` operator. This includes the start value but excludes the end value. |
10 | 18 |
|
11 | 19 | For example:
|
12 | 20 |
|
13 | 21 | ```kotlin
|
14 | 22 | fun main() {
|
15 | 23 | //sampleStart
|
16 |
| - // Closed-ended range |
| 24 | + // Closed-ended range: includes both 1 and 4 |
17 | 25 | println(4 in 1..4)
|
18 | 26 | // true
|
19 | 27 |
|
20 |
| - // Open-ended range |
| 28 | + // Open-ended range: includes 1, excludes 4 |
21 | 29 | println(4 in 1..<4)
|
22 | 30 | // false
|
23 | 31 | //sampleEnd
|
@@ -50,11 +58,10 @@ fun main() {
|
50 | 58 | ```
|
51 | 59 | {kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-ranges-downto"}
|
52 | 60 |
|
53 |
| -It is also possible to iterate over numbers with an arbitrary step (not necessarily 1). This is done via the |
54 |
| -[`step`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/step.html) function. |
| 61 | +You can also iterate over numbers with a custom step using the |
| 62 | +[`step()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/step.html) function, instead of the default increment of 1: |
55 | 63 |
|
56 | 64 | ```kotlin
|
57 |
| - |
58 | 65 | fun main() {
|
59 | 66 | //sampleStart
|
60 | 67 | for (i in 0..8 step 2) print(i)
|
|
0 commit comments