0
0
KotlinHow-ToBeginner · 3 min read

How to Use repeat Function in Kotlin: Simple Guide

In Kotlin, you use the repeat function to run a block of code a specific number of times. It takes an integer for how many times to repeat and a lambda with the code to execute each time.
📐

Syntax

The repeat function syntax is simple:

  • repeat(times: Int) { /* code */ }
  • times is how many times the code block runs.
  • The code block inside { } runs each time.
kotlin
repeat(3) {
    println("Hello")
}
Output
Hello Hello Hello
💻

Example

This example prints numbers from 0 to 4 using repeat. The lambda receives the current iteration index.

kotlin
fun main() {
    repeat(5) { index ->
        println("Number: $index")
    }
}
Output
Number: 0 Number: 1 Number: 2 Number: 3 Number: 4
⚠️

Common Pitfalls

One common mistake is forgetting that the lambda parameter is zero-based index, so it starts at 0, not 1. Another is using repeat with a negative number, which throws an exception.

Also, avoid using repeat for side effects without clear intent, as it can reduce code readability.

kotlin
fun main() {
    // Correct: starting index at 1 by adding 1
    repeat(3) { index ->
        println("Count: ${index + 1}") // Correct way to start from 1
    }

    // Wrong: negative times causes error
    // repeat(-1) { println("Won't run") } // Throws IllegalArgumentException
}
Output
Count: 1 Count: 2 Count: 3
📊

Quick Reference

UsageDescription
repeat(times) { code }Runs code block times times.
repeat(times) { index -> code }Runs code with zero-based index each time.
times must be >= 0Negative values cause an exception.
Lambda parameter is optionalYou can omit index if not needed.

Key Takeaways

Use repeat(times) { } to run code multiple times easily.
The lambda parameter is the zero-based index of the current iteration.
Passing a negative number to repeat causes an error.
You can omit the lambda parameter if you don't need the index.
Avoid using repeat for unclear side effects to keep code readable.