In Kotlin, ranges define a sequence of values with a start, an end, and an optional step. Ranges are widely used with loops, conditions, and collections to simplify iteration and value checking.
Ranges make your code concise, readable, and expressive. Instead of manually checking or looping through numbers, Kotlin lets you define a range using simple syntax.
for loops.if (x in 1..10).// Simple numeric range
for (i in 1..5) {
print("$i ")
}
// Output: 1 2 3 4 5
// Using 'downTo'
for (i in 5 downTo 1) {
print("$i ")
}
// Output: 5 4 3 2 1
// Using 'step'
for (i in 1..10 step 2) {
print("$i ")
}
// Output: 1 3 5 7 9
// Exclusive range using 'until'
for (i in 1 until 5) {
print("$i ")
}
// Output: 1 2 3 4
.. → Inclusive range (includes both start and end).until → Exclusive of the end value.downTo → Creates a descending range.step → Changes the increment or decrement value.forEach or functional operations instead.// Check if a value lies in a range
val score = 87
if (score in 80..100) {
println("Excellent!")
} else {
println("Keep trying!")
}
// Character ranges
for (ch in 'a'..'f') {
print("$ch ")
}
// Output: a b c d e f
// Using ranges in conditions
val age = 25
when (age) {
in 0..12 -> println("Child")
in 13..19 -> println("Teenager")
in 20..60 -> println("Adult")
else -> println("Senior")
}
// Nested ranges
for (x in 1..3) {
for (y in 1..2) {
println("x=$x, y=$y")
}
}
1..1_000_000_000 can consume memory or slow performance if iterated directly... and until in Kotlin?step function?in with a range?| Keyword | Description | Example |
|---|---|---|
.. | Inclusive range | 1..5 → 1,2,3,4,5 |
until | Exclusive range | 1 until 5 → 1,2,3,4 |
downTo | Descending range | 5 downTo 1 → 5,4,3,2,1 |
step | Change step value | 1..10 step 2 → 1,3,5,7,9 |
fun main() {
val numbers = 1..10
println("Numbers in range: ${numbers.joinToString()}")
val evenNumbers = (2..10 step 2).toList()
println("Even numbers: $evenNumbers")
for (i in 10 downTo 1 step 3) {
println("Counting down: $i")
}
val charRange = 'A'..'E'
println("Characters: ${charRange.joinToString()}")
}
Output:
Numbers in range: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Even numbers: [2, 4, 6, 8, 10]
Counting down: 10
Counting down: 7
Counting down: 4
Counting down: 1
Characters: A, B, C, D, E