Kotlin repeat()

Kotlin repeat()

In Kotlin, the repeat() function is used to execute a given block of code a specified number of times.

This function is useful when you need to perform a certain operation or run a piece of code iteratively without manually writing a loop.

In this tutorial, we’ll explore the syntax of the repeat() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the repeat() function is:

inline fun repeat(times: Int, action: (Int) -> Unit)

The repeat() function takes the number of times to repeat the action as its first argument and a block of code (lambda expression) as its second argument. The block of code is executed for each iteration, and the current iteration index is passed as an argument to the block.

Examples for repeat() function

1. Using repeat() to Print “Hello World” Multiple Times

In this example, we’ll use repeat() to print “Hello World” three times.

Kotlin Program

fun main() {
    repeat(3) {
        println("Hello World")
    }
}

Output

Hello World
Hello World
Hello World

In this example, the repeat() function is used to print “Hello World” three times. The specified block of code is executed for each iteration, resulting in the repeated output.

Summary

In this tutorial, we’ve covered the repeat() function in Kotlin, its syntax, and how to use it for executing a block of code a specified number of times.