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
CodePudding user response:
U can benefit on kotlin collections extensions and use List
builder
val list: List<Post> = List(Random.nextInt(0, 50)) {
getRandomPost()
}