repeat

repeat(n)

Example

repeat(n) { } runs a block n times. The current index (starting at 0) is available as it.

fun main() {
    repeat(3) {
        println("Sending OTP, try ${it + 1}")
    }
    repeat(5) { print("★") }
    println()
}

Output

Sending OTP, try 1
Sending OTP, try 2
Sending OTP, try 3
★★★★★

Which Loop to Use

LoopUse when
for (x in collection)going through every item of a list, set, map, string or array
for (i in a..b)counting through numbers
repeat(n)doing something exactly n times
whilerepeating until a condition changes, unknown count
do-whilethe body must run at least once
list.forEach { }functional style (no break/continue)