Table of contents
1.
Introduction
2.
Range Creation
2.1.
Range Creation with (..) operator
2.2.
Range creation with rangeTo() function
2.3.
Range creation with downTo() function
3.
Use Cases of Kotlin Ranges
3.1.
1. Checking if a value exists in Range or not
3.2.
2. Using break and continue in Range
3.3.
3. Range using forEach loop
3.4.
4. Modifying the default step()
3.5.
5. Using reversed()
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Ranges

Author Akshit Pant
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In simple terms, Range in Kotlin is a collection of finite values defined by starting and endpoints.

For a range, we want a start, an end/stop, a step. The start and stop define the beginning and end of the Range, and the step can be as per user requirement.

Start and Stop are both inclusive in Range and If the step is not altered, then by default, the step is 1.
In this blog we will be talking about Kotlin Ranges, how to create them, and also different types of methods like: rangeTo()downTo()reversed()step(). Let us start it with creation of our desired range.

Range Creation

The Range can be created in Kotlin in three ways

With the use of (..) operator

With the use of rangeTo() function

With the use of downTo() function

Range Creation with (..) operator

This operator builds a range from start to end, including the start and end values. It is the rangeTo() function’s operator form. 

Note: (..) operator can be used to create a range for both integers and characters.

Let us see the use of this operator using integer and character range.

Code:

fun main() {
    println("Example with Integer range:")
    for(num in 1..10){                                                 // creating range with start 1 and end 10
        println(num)
    }    
}


Output:

Example with Integer range:
1
2
3
4
5
6
7
8
9
10

Now, similarly, we can create a range with character range(see an example of char range from ‘a’ to ‘k’ given below).

Code:

fun main() {
     println("Example with Character range:")
    for(ch in 'a'..'k'){                        // creating range with start a and end k
        print(ch + " ")
    }   
}

Output:

Example with Character range:
a b c d e f g h i j k

Range creation with rangeTo() function

It is similar to the (..) operator. It will create a range up to the value passed as an argument. It is also used to create Range for integers as well as characters.

It works in the same way as the (..) operator. It will make a range to the value passed as argument in rangeTo(). It can also be used for making integer and character ranges.

Let us see an example of range creation with rangeTo().

Code:

fun main() {
         println("rangeTo() with Integer range:")
    for(x in 1.rangeTo(9)){
        println(x)
    }    
}

Output:

rangeTo() with Integer range:
1
2
3
4
5
6
7
8
9

Example of using rangeTo() for creation of char type range is given below:
Code:

fun main() {
    println("rangeTo() with Character  range:")
    for(x in 'a'.rangeTo('k')){
        println(x)
    }    
}

Output:

rangeTo() with Character  range:
a
b
c
d
e
f
g
h
i
j
k

Range creation with downTo() function

It works in the opposite direction of the rangeTo() or (..) operator. It generates a range in descending order, from larger to smaller values. In the examples below, we generate ranges in reverse order for both integers and characters.

Code:

fun main() {  
    println("downTo() with Integer range:")
    for(x in 10.downTo(5)){
        println(x)
    }
}

Output:

downTo() with Integer range:
10
9
8
7
6
5

Range creation of char type range with downTo() method is shown below:
Code:

fun main() {    
    println("downTo() with Character range:")
    for(ch in 'k'.downTo('a')){
        println(ch)
    }  
}

Output:

downTo() with Character range:
k
j
i
h
g
f
e
d
c
b
a

Use Cases of Kotlin Ranges

Now let us take a deep dive into Kotlin Ranges with some programming queries.

1. Checking if a value exists in Range or not

We can do so with the help of the 'in' operator. Let us see this with an example-

Code:

fun main() {
    val nums = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
if (5 in nums) {
  println("Yes, It exists!")
} else {
  println("#404 Error")
}}

Output:

Yes, It exists!

Here, In this example we checked if ‘5’ exists in range or not.

2. Using break and continue in Range

We can use the break and continue keywords in a range or a for-loop.

Code:

fun main() {for (num in 90..110) {
  if (num == 100) {              // loop works until num != 100
    break                                 // break ends the loop
  }
  println(num)
}
}

Output:

90
91
92
93
94
95
96
97
98
99

Here, The moment we encountered ‘100’ the break statement gets into action. 

3. Range using forEach loop

The use of forEach loop for traversing is shown below with an example-

Code:

fun main(args : Array<String>){
    println("Integer type Range")
    (4..10).forEach(::println)      // this will start loop with start 4 and end 10(both end inclusive)
}

Output:

Integer type Range
4
5
6
7
8
9
10

4. Modifying the default step()

One can add a step between values using the term step. 

It is primarily utilized in rangeTo()downTo(), and the (..) operator to change the default gap of 1 between two elements.

Note: The value of the step function can never be zero.

Let's see this with an example.

Code:

fun  main() {
    for (i in 3..10 step 2)      // for loop with step of 2
        println("$i ")
    }

Output:

3
5
7
9

5. Using reversed()

Use of reversed() is to reverse the given/specified Range. We can use the reverse() function instead of downTo() for printing the entire Range in descending order.

Let us use reversed() in a program.

Code:

fun  main() {
     var given_range = 5..15         // range start is 5 and end is 15
    for (i in given_range.reversed()){
        print("$i ")
    }
            }

Output:

15 14 13 12 11 10 9 8 7 6 5

In this example, we reversed the order of range from (5 to 15) to (15 to 5) using reversed() method.

Must Read Elvis Operator Kotlin

FAQs

  1. How can we change the default step of 1?
    We can do so with the use of (“step” + valueToStep), where step is keyword and valueToStep will be numeric value.
     
  2. How to find the min, max, sum, and average Range?
    This can be done using the predefined function in Kotlin Range library. So, predefined.min()predefined.max()predefined.sum() and predefined.average() can be used for easy solution.
     
  3. Is there any alternate of downTo() function?
    Yes, We can print the Range in reversed order by using reversed() function.

Key Takeaways

Cheers if you reached here! 

The purpose of this article was to introduce the reader to the Kotlin Ranges and give some basic idea about how to initialize and use them with their properties and functionalities. If anyone wants to set up their Kotlin environment for programming, then here is the help. If you want to learn more about the difference between Java and Kotlin, you can jump to this article which covers them in great detail.

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. 

Till then, Happy Learning!

Live masterclass