Is there a way to use kotlin MutableList and give ...
# announcements
s
Is there a way to use kotlin MutableList and give the backing ArrayList the initial capacity first without adding to the list an initialized component? As a micro-optimization, I used to use the Java List and give it the capacity up front if I knew it.
I see this is how it is currently implemented:
Copy code
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
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
}
But I am wondering why this does not exists:
Copy code
@kotlin.internal.InlineOnly
public inline fun <T> MutableList(size: Int): MutableList<T> {
    val list = ArrayList<T>(size)
    return list
}
r
can't you just write
ArrayList<T>(size)
?
you're expecting it to have some capacity, meaning you know you want an ArrayList
s
Well, yeah... I guess it would be that simple. That would work. I was just surprised the MutableList doesn't have the same functionality.
r
if you're asking for a capcity, you're not just asking for any MutableList, while if you're asking to init from size + init function you can just be asking for any old MutableList
s
I guess also Mutable list doesn't technically have to be backed by arraylist and implements List interface which knows nothing about initial capacity.
☝️ 1