Purpose of repeat function

Viewed 264

Using kotlin I can repeat an action in at least two ways:

val times = 5

// First option
for (i in 0 until times) {
    print("Action $i")
}

// Second option
repeat(times) {
    print("Action $it")
}

I'd like to know the purpose of repeat.

  • Should the traditional for loop be replaced with repeat function if possible?
  • Or are there special cases for this function?
  • Are there any advantages in repeat function?

EDIT

I've made some research about this question. As long as kotlin is open source project, I could download the sources and check git history.

I found that

1) repeat function is a replace for times function extension.

public inline fun Int.times(body : () -> Unit)

2) KT-7074. times function has become deprecated. But why?

3 Answers

Next lines are all just my opinion:

  • there are no special cases when you should or shouldn't use repeat function.
  • it has more concise syntax.
  • In places where you don't need to manipulate the loop counter or need to repeat only some simple action I would use that function.

It's all up to you to decide when and how to use it.

From Standard.kt:

/**
 * Executes the given function [action] specified number of [times].
 *
 * A zero-based index of current iteration is passed as a parameter to [action].
 *
 * @sample samples.misc.ControlFlow.repeat
 */
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {
        action(index)
    }
}

As you can see repeat(times) is actually for (index in 0 until times).
There is also a zero-based loop counter and it is: it.

Should the traditional for loop be replaced with repeat function if possible?

I can't find any reason for that

Or are there special cases for this function?

None I can think of.

Are there any advantages in repeat function?

None I can think of, or maybe(?) just 1:
for educational purposes, I suppose it's easier to teach
that repeat(n) { } performs n iterations of the block of statements inside the curly brackets.

It's just a matter of convenience (shortens the code). There are even more ways for example using an IntRange and forEach

(0..4).forEach {
    println(it)
}

0 1 2 3 4

They all serve the same purpose, so the choice is yours.

You don't need to worry about performance either, since repeat and forEach are inline functions, which means the lambda code is copied over to the call site at compile time.

Related