repeat in Kotlin explanation with example

repeat in Kotlin example:

repeat in Kotlin is used to repeat any one function for a specific number of times. We can use it like a loop in Kotlin.

Definition:

repeat is defined as below:

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

It executes the function action for t times. The current index is passed as a parameter to the function action.

Example of repeat to print a message 5 times:

Let’s take a look at the below program:

fun main(args: Array<String>) {
    repeat(5){
        println("Hello World !!")
    }
}

If you run it, it will print Hello World !! for 5 times.

Hello World !!
Hello World !!
Hello World !!
Hello World !!
Hello World !!

Getting the index :

repeat passes the current index starting from 0. For example:

fun main(args: Array<String>) {
    repeat(5){
        println("Index: $it")
    }
}

It will print:

Index: 0
Index: 1
Index: 2
Index: 3
Index: 4

If you give 0 as t, it will not run the inner function.

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊