Ranges in Kotlin Ranges in Kotlin

Page content

In this post, we’ll see quick examples of creating ranges using various range expressions and iterating over ranges in Kotlin.

Creating Ranges

We can create ranges in Kotlin using .. operator, rangeTo() and downTo() functions. Few points to note:-

  • .. operator is simplest way to create ranges.
  • Ranges are inclusive by default. For example, range 1..9 includes 1 and 9
  • Elements in range are incremented/decremented by one step by default. For example, numbers in range 1..9 are incremented by 1 by default and numbers in range 1..9 step 3 are incremented by 3.
  • Use until to exclude last element in range. For example, range 1 until 10 exclude 10
  • Create reverse range using downTo operator, downTo() function or reversed() function. For example, range 10 downTo 1 is 10 to 1

Let’s look at various examples of creating ranges for numbers:-

1..9                    // 123456789
1.rangeTo(5)            // 12345
5.downTo(1)             // 54321
5 downTo 1              // 54321
(1..5).reversed()       // 54321
1..9 step 2             // 13579
1..9 step 3             // 147
1 until 10              // 123456789

Similarly, we can create ranges for characters:-

'a'..'z'                // abcdefghijklmnopqrstuvwxyz
'A'..'Z'                // ABCDEFGHIJKLMNOPQRSTUVWXYZ
'a'.rangeTo('e')        // abcde
'E'.downTo('A')         // EDCBA
'e' downTo 'a'          // edcba
('A'..'Z').reversed()   // ZYXWVUTSRQPONMLKJIHGFEDCBA
'a'..'i' step 2         // acegi
'A'..'I' step 3         // ADG
'a' until 'e'           // abcd

Iterating Ranges

Now we know how to create ranges, let’s look at various examples to iterate over the ranges using for, forEach and iterator

Using for loop

for loop is well known to developers to iterate over the ranges:-

for (i in 1..9) print(i)
//Prints 123456789

for (i in 5 downTo 1) print(i)
//Prints 54321

for (ch in 'a'..'e') print(ch)
//Prints abcde

for (ch in 'E' downTo 'A') print(ch)
//Prints EDCBA

We can also use variables while creating and iterating ranges:-

val start = 1
val end = 9
val rangeOneToNine = start..end

for (i in rangeOneToNine) print(i)
//Prints 123456789

Using foreach() function

foreach function can be used directly on ranges or chained with other functions to iterate the result:-

(1..5).forEach(::print)
//Prints 12345

(1..5).reversed().forEach { i -> print("$i ") }
//Prints 5 4 3 2 1

'a'.rangeTo('z').step(5).forEach { print(it) }
//Prints AFKPUZ

Using iterator() function

Range also provide iterator function to iterate over the elements of a range:-

val chars = ('a'..'e')
val it = chars.iterator()
while (it.hasNext()) {
    print(it.next())
}
//Prints abcde

Filtering Ranges

We can apply filter() function on range to filter the elements by given predicate:-

var rangeOneToTen = 1..10;
    
rangeOneToTen.filter { it % 2 == 0 }.forEach(::print)
//Prints 246810

rangeOneToTen.filter { it % 2 != 0 }.forEach(::print)
//Prints 13579

We can also apply map and reduce functions on ranges:-

var rangeOneToFive = 1..5;

rangeOneToFive.map { it * it }.forEach{ print("$it, ")}
//Prints 1, 4, 9, 16, 25,

println(rangeOneToFive.reduce{a, b -> a + b})
//Prints 15

Ranges Math Functions

There are many math functions are available to use with ranges like min, max, count, sum, average, and random

var r = 1..10;
print(r.minOrNull()) //Prints 1
print(r.maxOrNull()) //Prints 10
print(r.count())     //Prints 10
print(r.sum())       //Prints 55
print(r.average())   //Prints 5.5
print(r.random())    //Prints random number from 1 to 10

The first, last, and step

We can get first, last, and step element from the ranges

val r = 18..31 step 3
r.forEach(::println)  //Prints 18 21 24 27 30
println(r.first)      //Prints 18
println(r.last)       //Prints 30
println(r.step)       //Prints 3