SoFunction
Updated on 2025-04-12

Sample code for the use of range operators in Kotlin (different usage of range operators)

Example of usage of range operators in Kotlin

Range operators are a very practical tool when programming using Kotlin in Android development. The following will introduce the different usages of range operators in Kotlin through a sample code.

Sample code

fun printRange(range: IntRange) {
    // traverse the entire range    for (i in range) {
        ("Tag",""+i);
    }
    // traverse the range with step size 2    for (i in range step 2) {
        ("Tag","step:"+i);
    }
    // Inverse order traversal from 6 to 1    for(i in 6 downTo 1) {
        ("Tag","downTo:"+i);
    }
    // traverse from 6 to 1 in reverse order in step size 2    for(i in 6 downTo 1 step 2) {
        ("Tag","downToStep:"+i);
    }
    // traverse in step size 2 from 1 to 10 (not including 10)    for(i in 1 until 10 step 2) {
        ("Tag","until:"+i);
    }
}

Code explanation

Traverse the entire range

for (i in range) {
    ("Tag",""+i);
}

This loop will go throughrangeand print each integer in it. Kotlin'sinKeywords, which can be used to determine whether an element is within a certain range, or to traverse the range.

traverse the range in step size 2

for (i in range step 2) {
    ("Tag","step:"+i);
}

stepKeywords are used to specify the step size when traversing the range. In this example, the loop will skip an element and print it outrangeevery other element in.

Inverse order traversal

for(i in 6 downTo 1) {
    ("Tag","downTo:"+i);
}

downToKeywords are used to create a range in reverse order. This cycle starts at 6, decrements to 1, and prints out each number.

Traversal in reverse order in step size 2

for(i in 6 downTo 1 step 2) {
    ("Tag","downToStep:"+i);
}

CombineddownToandstepKeywords can be used to reverse order and traverse with step size. In this example, the loop starts at 6, decrements by 2, until 1.

useuntilKeyword traversal

for(i in 1 until 10 step 2) {
    ("Tag","until:"+i);
}

untilKeywords are used to create a range that does not contain an end value. This cycle starts at 1, increments by 2, until 9 (not including 10).

Summarize

Kotlin's range operator provides a concise and powerful way to handle integer ranges. passinstepdownToanduntilKeywords can easily achieve various traversal requirements and improve the readability and maintainability of the code. In Android development, these operators can be used to handle various loop tasks, such as initialization of UI elements, traversal of data, etc.

This is the article about the sample code of scope operator usage in Kotlin (different usages of scope operators). For more related Kotlin scope operator content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!