Kotlin Ranges

Kotlin Ranges

Kotlin Range is a closed interval defined by two endpoint values.

Mathematically [x, y] is a range from x to y, including the x and y. Here, x and y are the end points of this range. In Kotlin, .. operator can be used to define this kind of a range, as shown in the following.

x..y

This range includes values from x to y, including the end points.

If you would like to define a range excluding the end point y, you can use until function.

x until y

If you would like to define a range from x to y with adjacent values having a specific difference of z, then use the step function, as shown in the following.

x..y step z

Based on the type of values in the range, a range can be an IntRange, a LongRange, a CharRange, etc.

Using a For loop, you can iterate over the values in a range.

1. Iterate over an integer range

In the following program, we take an integer range 4..9 and iterate over the range using a For loop.

Kotlin Program

fun main() {
    for (i in 4..9) {
        println(i)
    }
}

Output

4
5
6
7
8
9

2. Iterate over a character range

In the following program, we take a character range 'a'..'g' and iterate over the range using a For loop.

Kotlin Program

fun main() {
    for (ch in 'a'..'g') {
        println(ch)
    }
}

Output

a
b
c
d
e
f
g

Kotlin Ranges Tutorials

There are many operations that we can do on a Range in Kotlin, and the following tutorials cover these topics.

With other types