Kotlin: Kotlin – creating a mutable list with repeating elements

Kotlin Programming

Question or issue of Kotlin Programming:

What would be an idiomatic way to create a mutable list of a given length n with repeating elements of value v (e.g listOf(4,4,4,4,4)) as an expression.

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

How to solve this issue?

Solution no. 1:

Use:

val list = MutableList(n) {index -> v}

or, since index is unused, you could omit it:

val list = MutableList(n) { v }

Solution no. 2:

another way may be:

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

This style is compatible with both MutableList and (Read Only) List

Solution no. 3:

If you want different objects you can use repeat.
For example,

 val list = mutableListOf().apply {
   repeat(2){ this.add(index = it-1, element = "YourObject($it)") }
 }

Replace String with your object. Replace 2 with number of elements you want.

Hope this helps!