kotlin
  1. kotlin-working-ranges

Kotlin Working Ranges

In Kotlin, ranges can be used to represent a series of values between two endpoints. Kotlin provides several range types, including the ClosedRange, HalfOpenRange, and PartialRange. In this tutorial, we'll discuss how to work with ranges in Kotlin.

Syntax

The syntax for creating ranges in Kotlin is shown below:

val range = start..end

You can also create a range using the rangeTo() function:

val range = start.rangeTo(end)

To check if a value is within a range, you can use the in operator:

val range = 1..10
val value = 5

if (value in range) {
    println("Value is within the range")
}

Example

Let's say you want to create a program that prints all even numbers between 1 and 10. You can create a range between 1 and 10 and use a for loop to iterate over the values within the range:

fun main() {
    val range = 1..10

    for (i in range) {
        if (i % 2 == 0) {
            println(i)
        }
    }
}

Output

The output of the above program will be:

2
4
6
8
10

Explanation

In the example program, we created a range between 1 and 10 using the .. operator. We then used a for loop to iterate over the values within the range. In each iteration, we checked if the current value was even using the modulus operator. If the current value was even, we printed it to the console.

Use

Ranges can be used in a variety of scenarios, such as iterating over a series of values or checking if a value is within a certain range. They can help make your code more concise and easier to read and understand.

Important Points

  • Kotlin ranges are inclusive by default, meaning that both the start and end values are included in the range. To create an exclusive range, you can use the until function.
  • Range types in Kotlin differ based on the inclusivity of their endpoints. Closed ranges include both start and end values, half-open ranges include the start value but not the end value, and partial ranges include neither the start nor the end value.

Summary

Ranges are a powerful feature of Kotlin that can be used to represent series of values between two endpoints. Kotlin provides several range types to suit different use cases. In this tutorial, we covered the syntax, example, output, explanation, use, and important points of working with ranges in Kotlin. With this knowledge, you are now equipped to use ranges in your own Kotlin programs.

Published on: