Loops repeat work: while and do-while run according to a condition, while Kotlin’s idiomatic for form visits values supplied by an iterable. The usual shape is `for (item in elements)`, which runs once per element and makes that element available through the loop variable. section 2.4 section 2.4.3
Use `for` for collections, maps, and numeric progressions. Unlike Java’s classical C-style loop with initialization, condition, and update clauses, Kotlin replaces common counting-loop cases with ranges and progressions. `1..5` includes both endpoints; `1..<5` excludes the endpoint. `downTo` reverses direction, and `step` skips values. section 2.6 section 2.4.2
Listing 2.25 Initializing and iterating over a map
fun main() {
val binaryReps = mutableMapOf<Char, String>() #1
for (char in 'A'..'F') { #2
val binary = char.code.toString(radix = 2) #3
binaryReps[char] = binary #4
}
for ((letter, binary) in binaryReps) { #5
println("$letter = $binary")
}
// A = 1000001 D = 1000100
// B = 1000010 E = 1000101
// C = 1000011 F = 1000110
// (output split into columns for conciseness)
}
This example builds a binary lookup map by looping through the character range `A` through `F`, then iterates over map entries. Destructuring `(letter, binary)` separates each key-value pair directly in the loop header. section 2.4.3
Common loop patterns include:
- Iterate through a collection with `for (color in collection)` when each item is needed in turn. section 2.4.3
- Iterate through a map with destructuring, such as `for ((key, value) in map)`. section 2.4.3
- Keep an index without manual incrementing by iterating over `list.withIndex()` and destructuring the index and element. section 2.4.3
- Use `while` or `do-while` for condition-controlled repetition; use `break`, `continue`, and labels when nested-loop control requires it. section 2.4.1
`forEach` is a collection function that invokes a lambda for every element. It can be more concise than a regular `for` loop, but is not automatically preferable; use it where the lambda reads clearly. A lambda may also access and modify variables from its surrounding scope. section 5.1.4


























