🏎️ · Ranges

2 min read Β· Updated on by

Read on to find out about the concept of ranges in Kotlin, the in operator, and a brief mention of the associated infix functions β€” untildownTo , and step.


//sampleStart
fun main() {
    for(i in 0..3) { // 1.
        print(i)
    }
    print(" ")

    for(i in 0 until 3) { // 2.
        print(i)
    }
    print(" ")

    for(i in 2..8 step 2) { // 3.
        print(i)
    }
    print(" ")

    for (i in 3 downTo 0) { // 4.
        print(i)
    }
    print(" ")
}
//sampleEnd
  1. Iterates over a range starting from 0 up to 3 (inclusive). Like for (i=0; i<=3; ++i) in other C-based languages.
  2. Iterates over a range starting from 0 up to 3 (exclusive). Like the for loop in Python or like for(i=0; i< 3; ++i) in other C-based languages.
  3. Iterates over a range with a custom increment step for consecutive elements.
  4. Iterates over a range in reverse order

Now, this syntax might seem like it’s awfully ad-hoc, but in time, you’ll find out that everything here is actually something you can do yourself, usingΒ operatorsΒ andΒ infix functions. TheΒ ..Β andΒ inΒ are nothing but syntactic sugar for calls to theΒ rangeToΒ andΒ containsΒ operators, respectively. But all in due time β€” don’t worry about it for now.

Char ranges are also supported out of the box:


//sampleStart
fun main() {
    for (c in 'a'..'d') { // 1.
        print(c)
    }
    print(" ")

    for (c in 'z' downTo 's' step 2) { // 2.
        print(c)
    }
    print(" ")
}
//sampleEnd
  1. Iterates over a char range in alphabetical order
  2. Char ranges support step and downTo as well

Ranges are also useful in if statements:


//sampleStart
fun main() {
    val x = 2
    if (x in 1..5) { // 1.
        print("x is in range from 1 to 5")
    }
    println()

    if (x !in 6..10) { // 2.
        print("x is not in range from 6 to 10")
    }
}
//sampleEnd
  1. Checks if a value is in the range
  2. !in is the opposite of in

More info can be found in the docs.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer