listkotlin

Kotlin - creating a mutable list with repeating elements


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.


Solution

  • Use:

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

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

    val list = MutableList(n) { v }