Ranges and for Loops
| Since: | Kotlin 1.0(2016) |
|---|
A range in Kotlin is an object that represents an interval of values, created with .., until, and similar operators. Combined with a for loop, ranges let you write concise iteration.
Syntax
1..10 // 1 to 10 inclusive (closed range)
1 until 10 // 1 to 9 inclusive (open end, excludes 10)
10 downTo 1 // 10 down to 1 (descending)
1..10 step 2 // 1, 3, 5, 7, 9 (with step)
// Basic for loop syntax
for (variable in rangeOrCollection) {
// body
}
Syntax Reference
| Syntax | Description |
|---|---|
| a..b | A closed range from a to b, inclusive. Also works with characters. |
| a until b | A half-open range from a up to but not including b. Convenient for array index traversal. |
| a downTo b | A descending range from a down to b. |
| range step n | Sets the step size to n. |
| in range | Checks whether a value is contained in the range. |
| !in range | Checks whether a value is not contained in the range. |
| withIndex() | Iterates over a collection with both index and value. |
Sample Code
sample_range_for.kt
fun main() {
// Basic range loop
for (i in 1..5) {
print("$i ") // 1 2 3 4 5
}
println()
// Loop using until to exclude the end value
val list = listOf("A", "B", "C")
for (i in 0 until list.size) {
print("${list[i]} ") // A B C
}
println()
// Reverse loop using downTo
for (i in 5 downTo 1) {
print("$i ") // 5 4 3 2 1
}
println()
// Loop with a custom step size
for (i in 0..10 step 3) {
print("$i ") // 0 3 6 9
}
println()
// Iterating over a collection directly with for
val pilots = listOf("Ayanami Rei", "Ikari Shinji", "Soryu Asuka")
for (pilot in pilots) {
println(pilot)
}
// Use withIndex() to get both index and value
for ((index, value) in pilots.withIndex()) {
println("$index: $value")
}
// Using the in operator to check if a value is within a range
val score = 85
if (score in 70..89) {
println("Grade B")
}
// Ranges also work with characters
for (ch in 'A'..'E') {
print("$ch ") // A B C D E
}
}
The command looks like this:
kotlinc sample_range_for.kt -include-runtime -d sample_range_for.jar java -jar sample_range_for.jar 1 2 3 4 5 A B C 5 4 3 2 1 0 3 6 9 Ayanami Rei Ikari Shinji Soryu Asuka 0: Ayanami Rei 1: Ikari Shinji 2: Soryu Asuka Grade B A B C D E
Common Mistakes
fun main() {
val pilots = listOf("Ayanami Rei", "Ikari Shinji", "Soryu Asuka")
// using .. includes the end, causing an out-of-bounds index
// for (i in 0..pilots.size) { // 0..3 — pilots[3] throws IndexOutOfBoundsException
// println(pilots[i])
// }
// trying to use a negative step instead of downTo
// for (i in 5..-1) // This produces an empty range — it does not count down
// passing a negative step value causes a runtime error
// for (i in 0..10 step -2) // IllegalArgumentException: Step must be positive
}
Use until or indices for index-safe loops, downTo for descending loops, and downTo step for descending loops with a step.
sample_range_for_ok.kt
fun main() {
val pilots = listOf("Ayanami Rei", "Ikari Shinji", "Soryu Asuka")
// Use until to avoid out-of-bounds
for (i in 0 until pilots.size) {
println(pilots[i])
}
// Use downTo for descending loops
for (i in 3 downTo 1) {
println("Countdown: $i")
}
// Combine downTo with step for descending step loops
for (i in 10 downTo 0 step 3) {
print("$i ")
}
println()
}
The command looks like this:
kotlinc sample_range_for_ok.kt -include-runtime -d sample_range_for_ok.jar java -jar sample_range_for_ok.jar Ayanami Rei Ikari Shinji Soryu Asuka Countdown: 3 Countdown: 2 Countdown: 1 10 7 4 1
Notes
Kotlin ranges are commonly used for index-based iteration over collections. For iterating over array or list indices, list.indices is more concise than 0 until list.size. You can also control nested loops with labeled break and continue (e.g., break@outer).
Ranges can also be used inside when expressions (see when expression). For iteration using higher-order functions, see Higher-Order Functions.
If you find any errors or copyright issues, please contact us.