Kotlin Academy · Lesson

forEach, repeat, and forEachIndexed

Explore functional-style iteration helpers and when they beat classic loops.

Lesson 3 of 413 steps

forEach, repeat, and forEachIndexed is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

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.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “forEach, repeat, and forEachIndexed” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “forEach, repeat, and forEachIndexed”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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

  1. for Loop Over Ranges and Collections
  2. while and do-while: When to Use Each
  3. forEach, repeat, and forEachIndexed
  4. break, continue, and Labeled Returns
← Back to Kotlin Academy