Kotlin For Loop
The for...in loop is Kotlin's primary tool for iterating over ranges, arrays, and collections.
The for...in Syntax
Kotlin's for loop iterates over anything that provides an iterator - ranges, arrays, lists, sets, and maps all qualify. Unlike traditional C-style for loops with a counter, condition, and increment, Kotlin's for loop reads like natural language: for (item in collection).
Looping over a range
fun main() {
for (i in 1..5) {
println("Count: $i")
}
}Iterating Over Arrays and Lists
When you loop directly over a collection, the loop variable is bound to each element in turn, not an index. This is the most readable form and should be preferred whenever you don't need the position of the element.
Looping over a list
fun main() {
val languages = listOf("Kotlin", "Java", "Swift")
for (language in languages) {
println("I can learn $language")
}
}Accessing Index and Value Together
Sometimes you need both the position and the value. The withIndex() function wraps each element in an IndexedValue, which can be destructured directly in the loop header into an index and a value variable.
Looping with index and value
fun main() {
val scores = intArrayOf(88, 92, 76)
for ((index, score) in scores.withIndex()) {
println("Test ${index + 1}: $score points")
}
}Looping Over Maps
Maps can be destructured into key-value pairs directly inside the loop header, avoiding manual calls to entry.key and entry.value.
Destructuring a map
fun main() {
val capitals = mapOf("France" to "Paris", "Japan" to "Tokyo")
for ((country, capital) in capitals) {
println("$capital is the capital of $country")
}
}When to Use Which Form
- for (x in collection) - when you only need the values
- for (i in collection.indices) - when you need the index but the collection isn't a map
- for ((i, x) in collection.withIndex()) - when you need both index and value together
- for ((k, v) in map) - when iterating a Map and you need both key and value
Exercise: Kotlin For Loop
What kinds of things can a Kotlin for loop iterate over?