0

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

1 Answer 1

3

U can benefit on kotlin collections extensions and use List builder

val list: List<Post> = List(Random.nextInt(0, 50)) {
      getRandomPost()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.