Kotlin-创建具有重复元素的可变列表

使用值为 v(例如 listOf(4,4,4,4,4))的重复元素作为表达式创建给定长度 n的可变列表的惯用方法是什么。

我正在做 val list = listOf((0..n-1)).flatten().map{v},但它只能创建一个不可变的列表。

30688 次浏览

Use:

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

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

val list = MutableList(n) { v }

another way may be:

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

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

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.