-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
Repeat is a Kotlin function defined by the standard library for, you guessed it, repeating code. It fits nicely in with our discussion on loops. The repeat function is a clean way to run a block of code a fixed number of times without manually managing a loop variable. By fixed, I mean the number of repeats is determined by the value used with the repeat syntax, but our code can determine that value during app execution. Some examples will make things clearer.
Here is a basic example of repeat.
repeat(3) {
Log.d("RepeatExample", "Hello from repeat!")
}
In the preceding code, repeat(3) will execute the code inside the block 3 times.
Repeat is shorter and cleaner than a for loop when you don't need a specific range, and it avoids creating an explicit loop variable like i.
There is more to talk about regarding repeat. Inside the block, you can optionally use the implicit index parameter (called it) to get the current iteration number. In the previous example...