Kotlin - creating a mutable list with repeating elements

What will be the idiomatic way of creating a mutable list of a given length n with repeating elements of v (for example, listOf(4,4,4,4,4) ) as an expression.

I am doing val list = listOf((0..n-1)).flatten().map{v} , but it can only create an immutable list.

+21
list kotlin
source share
2 answers

Using:

 val list = MutableList(n) {index -> v} 
+46
source share

Another way could be:

 val list = generateSequence { v }.take(4).toMutableList() 

This style is compatible with both MutableList and list (read-only)

0
source share

All Articles