forEach, repeat, and forEachIndexed
Explore functional-style iteration helpers and when they beat classic loops.
forEach, repeat, and forEachIndexed is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Functional Iteration
Beyond for, Kotlin offers higher-order iteration: forEach, forEachIndexed, and repeat. They make small loops more expressive.
forEach Basics
forEach takes a lambda and runs it for every element. The element is implicitly named it.
fun main() {
val items = listOf("a", "b", "c")
items.forEach { println(it) }
}forEach with Named Parameter
Give the lambda parameter a clearer name when it reads poorly.
fun main() {
val users = listOf("Alice", "Bob", "Charlie")
users.forEach { name ->
println("Hello, $name!")
}
}repeat for Fixed Iterations
repeat(n) runs its block exactly n times. The lambda receives the iteration index (0-based).
fun main() {
repeat(5) {
println("Iteration $it")
}
}repeat for Side Effects
Use repeat for simple n-times actions: printing a separator, retrying a call, etc.
fun main() {
repeat(3) { println("-".repeat(20)) }
}forEachIndexed
forEachIndexed provides both the index and the element to the lambda.
fun main() {
val words = listOf("Hello", "Kotlin", "World")
words.forEachIndexed { index, word ->
println("$index: $word")
}
}forEach vs for
forEach is concise but loses break/continue. Use a traditional for if you need to exit early.
fun main() {
val nums = listOf(1, 2, 3, 4, 5)
// forEach: runs to completion
nums.forEach { print("$it ") }
println()
// for: can break
for (n in nums) {
if (n == 3) break
print("$n ")
}
println()
}Returning from forEach
You can simulate continue in forEach with a labeled return@forEach.
fun main() {
listOf(1, 2, 3, 4).forEach {
if (it % 2 == 0) return@forEach // skip
println("odd: $it")
}
}forEach on a Map
forEach on a map exposes each Map.Entry as it; destructure for readability.
fun main() {
val scores = mapOf("Alice" to 9, "Bob" to 7)
scores.forEach { (name, score) ->
println("$name -> $score")
}
}Chaining repeat with Other Calls
repeat returns Unit, so you cannot chain it functionally. Use it for side effects only.
fun main() {
var sum = 0
repeat(10) { sum += it }
println("Sum 0..9 = $sum") // 45
}Performance Note
For tight loops over large collections, plain for is slightly faster because it avoids creating a lambda. For clarity, prefer forEach.
fun main() {
val n = 1_000_000
var sum = 0L
for (i in 1..n) sum += i
println(sum)
}Quick Check
Which construct provides both an index and an element to its lambda?
Recap
forEach: lambda per element. forEachIndexed: index + element. repeat(n): fixed n-times loop. None support classic break — use for for early exit.
Frequently asked questions
Is the “forEach, repeat, and forEachIndexed” lesson free?
Yes — the full text of “forEach, repeat, and forEachIndexed” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “forEach, repeat, and forEachIndexed”?
Explore functional-style iteration helpers and when they beat classic loops. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “forEach, repeat, and forEachIndexed” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- for Loop Over Ranges and Collections
- while and do-while: When to Use Each
- forEach, repeat, and forEachIndexed
- break, continue, and Labeled Returns