Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of repeat function

Tags:

kotlin

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?

like image 565
Feedforward Avatar asked Feb 15 '26 01:02

Feedforward


1 Answers

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.

like image 190
Willi Mentzel Avatar answered Feb 16 '26 20:02

Willi Mentzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!