is there any utility method that repeatedly calls ...
# getting-started
b
is there any utility method that repeatedly calls a lambda on itself for n times? E.g. 2.repeat(3) { it + 1 } would add +1 to 3 2 times
1
r
Not in the stdlib as far as I know, but that's pretty easy to write yourself:
Copy code
inline fun <T> T.repeat(
    count: Int,
    action: (T) -> T,
): T {
    var x = this
    kotlin.repeat(count) {
        x = action(x)
    }
    return x
}
b
yeah, that's what I did, but did not know about kotlin.repeat, thanks
Copy code
fun <T> Int.repeat(initial: T, block: (T) -> T): T {
    var accumulator = initial
    kotlin.repeat(this) {
        accumulator = block(accumulator)
    }
    return accumulator
}
r
Ah, you have the count out front. In that case you might want to go with a different name to not confuse it with Kotlin's
repeat
signature, but that's just a personal preference.
b
thank you
👍 1
r
Maybe something along the lines of
fold
(e.g.
foldN
?) since that's probably closer in meaning to what you're doing. (compare Kotlin's various
fold
functions)
y
You could also do
(0..2).fold(3) { it, _ -> it + 1 }
but it's kinda ugly because it passes the index in
k
Another way:
generateSequence(3) { it + 1 }.take(1 + 2).last()
(it's 1 + 2 because the seed (3) is counted as the first element, and you want another 2).
e
why not just
Copy code
generateSequence(3) { it + 1 }.elementAt(2)
👍 1
1