Kotlin Range Operators

Introduction

Kotlin offers a diverse set of solutions. The majority of these solutions are designed to make development simpler and faster. Kotlin makes it easier to do specified tasks. Its functions and methods ensures that your code is more efficient because it is compiled in the same way as Java.

Java's boilerplate code is also significantly reduced. We'll look at one of the answers it provides: iterations. Ranges in Kotlin will be discussed in this post.

Ranges

A range is a set of values defined by a start and end value. A simple example would be the values 1 through 5 forming a range. That is, a range of 1 to 5 as the start and end values. The range includes both the start and finish values.

In other terms, a range is an interval between the start and end values. Functions can be used to generate progressions and check for values in ranges. Let's have a look at how we can use ranges.

You can execute the functions using the following repl.it before we start writing code. All you have to do is use the main function to call the appropriate function.

There are three ways for creating Range in Kotlin –

  • Using (..) operator

  • Using rangeTo() function

  • Using downTo() function

Using (..) operator

It is the most basic approach to interact with range. It will generate a range from start to end that includes both the start and end values. It is the rangeTo() function's operator form. We can construct ranges for integers and characters by using the (..) operator. Integer range Kotlin program with (..) operator.

fun main(args : Array<String>){

    println("Integer range:")
    // creating integer range
    for(num in 1..5){
        println(num)
    }
}

Output

Integer range:
1
2
3
4
5

Kotlin program of character range using (..) operator

fun main(args : Array<String>){

    println("Character range:")
    // creating character range 
    for(ch in 'a'..'d'){
        println(ch)
    }
}

Output

Character range:
a
b
c
d

Using rangeTo() function

It is similar to the (... It will generate a range up to the provided value. It is also used to generate ranges for numbers and characters. Using the rangeTo() method in Kotlin, create an integer range program.

fun main(args : Array<String>){

    println("Integer range:")
    // creating integer range 
    for(num in 1.rangeTo(5)){
        println(num)
    }
}

Output

Integer range:
1
2
3
4
5

Kotlin program of character range using rangeTo() function


fun main(args : Array<String>){

    println("Character  range:")
    // creating character range
    for(ch in 'a'.rangeTo('e')){
        println(ch)
    }
}

Output

Character  range:
a
b
c
d
e

Using downTo() function

It is the inverse of the rangeTo() or (... It generates a range in decreasing order, from larger to smaller values. In this section, we will define ranges in reverse order for both integers and characters.

Kotlin program of integer range using downTo() function –

fun main(args : Array<String>){

    println("Integer range in descending order:")
    // creating integer range
    for(num in 5.downTo(1)){
        println(num)
    }
}

Output

Integer range in descending order:
5
4
3
2
1

Kotlin program of character range using downTo() function –

fun main(args : Array<String>){

    println("Character range in reverse order:")
    // creating character range
    for(ch in 'e'.downTo('a')){
        println(ch)
    }
}

Output:

Character range in reverse order:
e
d
c
b
a

To create range using Foreach loop

The forEach loop is also used to traverse over the range.

fun main(args : Array<String>){

    println("Integer  range:")
    // creating integer range
    (2..5).forEach(::println)
}

Output:

Integer  range:
2
3
4
5

To Create Special Loops

We can describe how the loop occurs using loops derived from ranges. We might want it to skip one value while it loops. When you need to print either even or odd numbers, this is an useful use case.

In the case of an even number, the starting point would be 1 until the last point. The step keyword with the value 2 is then added. It will loop from 1 to 10, skipping one number along the way.

Here is an example of the rangeWithStep function.

fun rangeWithStep(){
    for(i in 1..10 step 2) print("$i,")
}

The output is:

1,3,5,7,9,

To Check For Values in Ranges

You may be required to check if a value is inside a certain range at times. For example, after selecting a picture with Android's intents, we can inspect its dimensions.

If we need the image dimensions to be within a certain range, we can use the range operator. Instead, an if statement is utilized. If the value is within the range, the result is true; otherwise, the result is false.

fun checkInRange(){
    val value = (1..10).random()
    if(value in 1..5) println("$value is in range")
    else println("$value is not in range")
}

In the checkInRange function, we are generating a random number between 1 and 10. Then we check if the value is between 1 and 5. We then print the result based on the comparison

Output

5 is in range
7 is not in range

Conclusion

As you can see, Ranges may make a variety of operations easier. It makes loop generation easier and more efficient.