Elye
Elye

Reputation: 60081

Looping through Kotlin x times, but not using the index

I want to loop through x times.

    for (i in 0 until x - 1) {
        // Do something.
    }

But I don't need to use the i. Is there a way better way to write the for-loop, without need to set the i?

Upvotes: 4

Views: 2598

Answers (2)

user8320224
user8320224

Reputation: 228

repeat(10) { _ ->
  println("Hello, world!")
}

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

A range is iterable. So to loop exactly x times, something like this would work:

(0 until x).forEach {
    // ...
}

An even simpler approach is this:

repeat(x) {
    // ...
}

Note that in both cases, the index is still accessible via the implicit it lambda parameter.

Upvotes: 15

Related Questions