Updated Answer
I was actually confused with capacity and size. There is no implementation of using a default capacity MutableList currently in Kotlin stdlib.
You can make one yourself.
fun <T> mutableListWithCapacity(capacity: Int): MutableList<T> =
ArrayList(capacity)
// creates a MutableList of Int with capacity of 5.
val mutableList = mutableListWithCapacity<Int>(5)
Outdated Answer
One of the reason why mutableListOf does not allow for default capacity is because default values in kotlin is not null.
However there is a utility function defined in kotlin.collections
package.
public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
val list = ArrayList<T>(size)
repeat(size) { index -> list.add(init(index)) }
return list
}
You can create a List with a List function or MutableList function with a default capacity and its mapping.
// creates a list of ints with default capacity of 10 and having nulls.
// But I highly doubt you should initialize it with a null since Kotlin is a null-safe language.
val list = MutableList<Int?>(10) { null }
But since there should not be nulls in Kotlin if it is intended use of non-null list else you have to do a null check using operators like ?.
!!.
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…