Melio500
Melio500

Reputation: 459

Making variable sized immutable list in Kotlin

I try to make a variable sized immutable list in Kotlin, but the only way I found is this. Isn't there a more clean way to do it ?

val size = nextInt(0, 50)
val list = mutableListOf<Post>()
for (i in 0..size) {
    list.add(getRandomPost())
}
val immutableList = Collections.unmodifiableList(list)

When my source is another list (with random size) I can do val immutableList = otherList.map{ /* thing that will be add() */ } but found nothing similar for just integrer

Upvotes: 0

Views: 325

Answers (1)

P.Juni
P.Juni

Reputation: 2485

U can benefit on kotlin collections extensions and use List builder

val list: List<Post> = List(Random.nextInt(0, 50)) {
      getRandomPost()
}

Upvotes: 3

Related Questions