Kotlin repeat() executes a block of code a specified number of times. It is useful when the number of iterations is known and you do not need to work with a custom range.
The repeat() function is part of the Kotlin standard library. It passes the current zero-based iteration index to its lambda, so the index is available when the repeated operation needs a counter.
Kotlin repeat() syntax
repeat(times) { index ->
// Statements to execute
}
The times argument specifies how many times the block should run. The optional index parameter starts at 0 and increases by one after each iteration.
- If
timesis greater than zero, the lambda runs that many times. - If
timesis zero, the lambda is not executed. - If
timesis negative, the lambda is also not executed. - The iteration index ranges from
0totimes - 1.
Example 1 – Kotlin repeat()
In this example, we will use a repeat statement to execute print statement 4 times.
Kotlin Program – example.kt
fun main(args: Array) {
repeat(4) {
println("Hello World!")
}
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
You can have any number of statements inside repeat block.
Use the iteration index in Kotlin repeat()
The lambda parameter supplied by repeat() contains the current iteration index. The first iteration receives 0, the second receives 1, and so on.
fun main() {
repeat(4) { index ->
println("Iteration index: $index")
}
}
Output
Iteration index: 0
Iteration index: 1
Iteration index: 2
Iteration index: 3
To display a counter beginning with 1, add one to the supplied index.
fun main() {
repeat(3) { index ->
println("Attempt ${index + 1}")
}
}
Output
Attempt 1
Attempt 2
Attempt 3
Execute multiple statements inside repeat()
The repeated lambda can contain calculations, assignments, function calls, and other Kotlin statements.
fun main() {
var total = 0
repeat(5) { index ->
val value = index + 1
total += value
println("Added $value, total = $total")
}
}
Output
Added 1, total = 1
Added 2, total = 3
Added 3, total = 6
Added 4, total = 10
Added 5, total = 15
Kotlin repeat() with zero or negative times
A repeat() block is skipped when its argument is zero or negative. No exception is thrown merely because the count is negative.
fun main() {
repeat(0) {
println("This is not printed")
}
repeat(-3) {
println("This is also not printed")
}
println("Program completed")
}
Output
Program completed
Repeat a character or string in Kotlin
Kotlin also provides String.repeat(), which returns a new string containing the original string repeated a specified number of times. This is different from the top-level repeat() function that executes a code block.
fun main() {
val stars = "*".repeat(5)
val word = "Hi ".repeat(3)
println(stars)
println(word)
}
Output
*****
Hi Hi Hi
Use the top-level repeat(5) { ... } function to execute statements five times. Use "*".repeat(5) when you need a repeated string value.
Kotlin repeat() compared with a for loop
Both repeat() and a for loop can execute code a known number of times. The better choice depends on whether the loop needs a range, custom step, or specific starting value.
| Requirement | Suitable construct |
|---|---|
| Run a block exactly N times | repeat(N) |
| Use a zero-based index | repeat(N) { index -> ... } |
| Iterate from one number to another | for with a range |
| Use a custom increment or decrement | for with step or downTo |
| Repeat until a condition changes | while or do-while |
The following two examples both print the numbers from zero through three.
fun main() {
repeat(4) { index ->
println(index)
}
for (index in 0 until 4) {
println(index)
}
}
repeat(4) is shorter when the intent is simply to perform four iterations. A for loop is clearer when the range itself carries meaning.
How to skip or stop iterations in Kotlin repeat()
Kotlin does not allow an ordinary break or continue statement directly inside the lambda passed to repeat(). A labeled return can skip the remaining statements in the current iteration.
fun main() {
repeat(5) { index ->
if (index == 2) {
return@repeat
}
println(index)
}
}
Output
0
1
3
4
Here, return@repeat behaves similarly to continue by ending only the current lambda invocation. To stop the repetition completely, use a loop such as for or while when practical.
fun main() {
for (index in 0 until 5) {
if (index == 2) {
break
}
println(index)
}
}
Output
0
1
Kotlin repeat() in Android code
The same repeat() function can be used in Android projects for operations such as creating a fixed number of model objects, adding placeholder items, or initializing test data.
data class MenuItem(
val id: Int,
val title: String
)
fun createMenuItems(): List<MenuItem> {
val items = mutableListOf<MenuItem>()
repeat(4) { index ->
items.add(
MenuItem(
id = index,
title = "Item ${index + 1}"
)
)
}
return items
}
Avoid using a fast repeat() loop to perform long-running work on the Android main thread. Database access, network requests, and CPU-intensive operations should use an appropriate coroutine dispatcher or background-processing API.
Common mistakes with Kotlin repeat()
- Expecting the index to start at one: the supplied index starts at zero. Use
index + 1for a one-based counter. - Using repeat() for an unknown number of iterations: use a
whileloop when repetition depends on a changing condition. - Trying to use break directly: ordinary
breakis not available inside therepeat()lambda. - Confusing repeat() with String.repeat(): one executes a lambda, while the other constructs a repeated string.
- Blocking the Android UI thread: repeating an expensive operation synchronously can make the interface unresponsive.
Kotlin repeat() FAQs
Does the Kotlin repeat() index start at zero?
Yes. For repeat(4), the supplied index values are 0, 1, 2, and 3.
Can break be used inside Kotlin repeat()?
An ordinary break cannot be used directly inside the lambda passed to repeat(). Use return@repeat to skip the rest of the current iteration, or choose a for or while loop when the repetition must stop early.
What happens when repeat() receives zero?
The lambda is not executed. The same applies when the specified number of repetitions is negative.
How do you repeat a character N times in Kotlin?
Convert the character to a string and use String.repeat(), such as "*".repeat(5). This returns "*****".
Should repeat() or a for loop be used in Kotlin?
Use repeat() when a block should run a fixed number of times and a zero-based index is sufficient. Use a for loop when you need a meaningful range, a custom starting value, a step, descending iteration, or early termination with break.
Kotlin repeat() editorial QA checklist
- Verify that every
repeat(times)example executes exactly the stated number of iterations. - Confirm that iteration-index explanations consistently describe zero-based values.
- Keep the distinction between the top-level
repeat()function andString.repeat()clear. - Check that examples discussing early exit do not incorrectly place an ordinary
breakinside the lambda. - Ensure Android examples do not recommend long-running synchronous work on the main thread.
Summary of Kotlin repeat()
In this Kotlin Tutorial, we learned how to use repeat() to execute a block a fixed number of times, access its zero-based iteration index, skip an iteration with a labeled return, compare it with Kotlin loops, and repeat strings or characters with String.repeat().
TutorialKart.com