https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Karlo Lozovina

02/02/2022, 7:52 PM
is there a function like
repeat
that collects the output of the lambda it executes? shorter version of
(1..times).map { ... }
e

ephemient

02/02/2022, 8:04 PM
Copy code
List(times) { ... }
😄 1
j

Joffrey

02/02/2022, 8:04 PM
You could use
List(n) { i -> ... }
You beat me to it, was trying to format that crap on the phone 😆
e

ephemient

02/02/2022, 8:05 PM
also
Copy code
generateSequence { ... }.take(times)
if you want it lazily
typing code on a phone is never great :-/
👍 1
k

Karlo Lozovina

02/02/2022, 8:09 PM
I think I'll go with
List(times)
although,
repeatMap
could be usefull...
🤔 1
j

Joffrey

02/02/2022, 8:13 PM
In what way would
repeatMap
be any different?
k

Karlo Lozovina

02/02/2022, 8:14 PM
It wouldn't behave any differently... just a shorter name for the idiom
r

Ruckus

02/02/2022, 8:15 PM
I'm pretty sure
repeatMap
is not shorter than
List
...
2
k

Karlo Lozovina

02/02/2022, 8:17 PM
hah, true 😄 maybe only a bit more readable... maybe 😄
t

todd.ginsberg

02/02/2022, 8:41 PM
You could always define your own extension for this, if you really want some syntax sugar:
Copy code
infix fun <T> Int.times(fn: (Int) -> T): List<T> =
    List(this) { fn(it) }

val list = 10 times {
    "I am only kidding... or am I?"
}
👍 1
e

ephemient

02/02/2022, 8:46 PM
very ruby looking - but their
#times
is like Kotlin's
repeat
t

todd.ginsberg

02/02/2022, 10:11 PM
Yeah, for sure.
11 Views