0
0
KotlinConceptBeginner · 3 min read

What is Range Operator in Kotlin: Simple Explanation and Examples

In Kotlin, the range operator is represented by .. and creates a sequence of values from a start to an end point. It is commonly used to loop through numbers or check if a value falls within a specific range.
⚙️

How It Works

The range operator .. in Kotlin creates a continuous sequence of values between two endpoints, including both the start and the end. Think of it like a ruler where you mark the start and end points, and every number in between is included.

For example, 1..5 means all numbers from 1 to 5: 1, 2, 3, 4, and 5. This operator works with numbers, characters, and other comparable types. It is very handy when you want to repeat an action a certain number of times or check if a value lies within a range.

💻

Example

This example shows how to use the range operator to print numbers from 1 to 5 and check if a number is within a range.

kotlin
fun main() {
    // Using range operator to loop from 1 to 5
    for (i in 1..5) {
        println(i)
    }

    val number = 3
    // Check if number is in the range 1 to 5
    if (number in 1..5) {
        println("$number is within the range 1 to 5")
    } else {
        println("$number is outside the range")
    }
}
Output
1 2 3 4 5 3 is within the range 1 to 5
🎯

When to Use

Use the range operator when you want to work with a sequence of values in a simple and readable way. It is perfect for loops where you need to repeat something a fixed number of times, like counting or iterating through a list of indexes.

It is also useful for checking if a value falls within a certain boundary, such as validating user input, filtering data, or controlling program flow based on ranges.

Key Points

  • The range operator .. creates an inclusive range from start to end.
  • It works with numbers, characters, and other comparable types.
  • Ranges can be used in loops and conditional checks.
  • It makes code simpler and easier to read when dealing with sequences.

Key Takeaways

The Kotlin range operator .. creates a sequence including both start and end values.
Use ranges to loop through numbers or check if a value lies within limits.
Ranges improve code readability and reduce manual checks.
They work with numbers, characters, and other comparable types.