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
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
}
thank you
👍 1
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