Kotlin – For Loop: Iterate Collections, Ranges & Arrays
Introduction – Why Learn Kotlin For Loops?
In Kotlin, the for loop is a powerful and concise way to iterate over collections, ranges, arrays, and strings. It eliminates boilerplate code found in traditional Java loops while adding readability and expressive power to Kotlin applications.
In this guide, you’ll learn:
- How Kotlin
forloop works with different data types - Looping through ranges, arrays, collections, and strings
- Using
indices,withIndex(), andstepcontrol - Real-world examples and best practices
Basic For Loop Over a Range
for (i in 1..5) {
println("Count: $i")
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
1..5defines a closed range from 1 to 5.iis the loop variable.
Looping with Step, DownTo, and Until
step – Custom Increment
for (i in 1..10 step 2) {
println(i)
}
Output: 1 3 5 7 9
downTo – Reverse Order
for (i in 5 downTo 1) {
println(i)
}
Output: 5 4 3 2 1
until – Exclusive Upper Bound
for (i in 0 until 5) {
println(i)
}
Output: 0 1 2 3 4 (excludes 5)
Iterating Through Arrays and Lists
Array Iteration
val nums = arrayOf(10, 20, 30)
for (n in nums) {
println(n)
}
List Iteration
val names = listOf("Alice", "Bob", "Charlie")
for (name in names) {
println("Hi $name")
}
Iterating Through a String
val text = "Kotlin"
for (char in text) {
println(char)
}
Output: K o t l i n
Accessing Index with indices and withIndex()
Using indices:
val items = listOf("A", "B", "C")
for (i in items.indices) {
println("Item at $i is ${items[i]}")
}
Using withIndex():
val items = listOf("X", "Y", "Z")
for ((index, value) in items.withIndex()) {
println("Item #$index = $value")
}
Nested For Loops
for (i in 1..2) {
for (j in 1..3) {
println("i=$i, j=$j")
}
}
Best Practices
| Tip | Why It Matters |
|---|---|
Use withIndex() over manual indexing | Cleaner and safer |
Use step and downTo for better control | Simplifies loop direction logic |
Prefer for over while when range/collection is known | More readable and idiomatic |
Common Mistakes
| Mistake | Fix |
|---|---|
Off-by-one with until or .. | Remember .. includes end, until does not |
| Using Java-style loops unnecessarily | Use Kotlin idioms like for (item in list) |
| Ignoring index when needed | Use withIndex() or indices |
Summary – Recap & Next Steps
Kotlin’s for loop is versatile and concise, supporting ranges, collections, and strings with clean syntax. It improves on Java’s loop constructs and promotes more readable and maintainable code.
Key Takeaways:
- Use
for (item in collection)for safe and clean iteration. - Use
step,downTo, anduntilfor control. - Access indices with
indicesorwithIndex(). - Prefer
forwhen looping over known-size sequences.
Practical Use:
Ideal for iterating API results, processing form inputs, looping UI elements, and data validation in Android or server-side Kotlin apps.
FAQs – Kotlin For Loop
Can I loop in reverse in Kotlin?
Yes. Use downTo:
for (i in 10 downTo 1) { ... }
What’s the difference between .. and until?
.. is inclusive, until excludes the upper bound:
1..5 → 1 2 3 4 5
1 until 5 → 1 2 3 4
How do I get both index and value in a loop?
Use withIndex():
for ((i, v) in list.withIndex()) { ... }
Can I use for to iterate over a map?
Yes:
val map = mapOf("A" to 1, "B" to 2)
for ((key, value) in map) {
println("$key -> $value")
}
Is for better than while in Kotlin?
Use for when iterating over collections or ranges. Use while for unknown bounds or conditional loops.
Share Now :
