Basel Shishani
Basel Shishani

Reputation: 8197

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.

Upvotes: 113

Views: 49546

Answers (5)

noev
noev

Reputation: 980

I like this infix syntax

val list = n of Item

public infix fun <A> Int.of(that: A): MutableList<A> =
    buildList { repeat(this@of) { add(that) } }.toMutableList()

Upvotes: 0

provisota
provisota

Reputation: 1660

You're able to use the ranges for this purpose, e.g.

        val listOfFour = (1..10).map { 4 }

or

        val objectList = (1..10).map {
            YourClass(
                arg1 = "someValue",
                arg2 = it                
            )
        }

if you need you can use it (index) for your needs as well.

Upvotes: 13

Shivanand Darur
Shivanand Darur

Reputation: 3224

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

 val list = mutableListOf<String>().apply {
   repeat(2){ this.add(element = "YourObject($it)") }
 }

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

Upvotes: 10

voddan
voddan

Reputation: 33839

Use:

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

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

val list = MutableList(n) { v }

Upvotes: 217

Alpha Ho
Alpha Ho

Reputation: 584

another way may be:

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

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

Upvotes: 35

Related Questions