Kotlin Ranges

Kotlin Ranges

In Kotlin, ranges are used to represent a sequence of values. They are commonly used with loops, conditions, and collections.


1. Basic Range (..)

The .. operator creates a range including both start and end values.

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

for (i in range) {
println(i)
}
}

Output:

1
2
3
4
5

2. until Range (End Not Included)

for (i in 1 until 5) {
println(i)
}

Output:

1
2
3
4

3. Reverse Range (downTo)

for (i in 5 downTo 1) {
println(i)
}

4. Step in Range (step)

for (i in 1..10 step 2) {
println(i)
}

Output:

1
3
5
7
9

5. Character Range

for (ch in 'a'..'e') {
println(ch)
}

6. Check Value in Range (in / !in)

val x = 7

if (x in 1..10) {
println("x is in range")
}

if (x !in 1..5) {
println("x is not in range 1 to 5")
}


7. Ranges with when

val marks = 85

when (marks) {
in 90..100 -> println("Grade A")
in 75..89 -> println("Grade B")
in 50..74 -> println("Grade C")
else -> println("Fail")
}


8. Floating-Point Ranges (Not Directly Supported)

❌ This does NOT work:

// 1.0..5.0 (Invalid)

✅ Alternative:

val range = 1..5
for (i in range) {
println(i.toDouble())
}

9. Useful Range Properties

val r = 1..5

println(r.first) // 1
println(r.last) // 5
println(r.step) // 1


Summary

  • .. → inclusive range

  • until → excludes end value

  • downTo → reverse range

  • step → custom increment

  • Works with for, if, when

You may also like...