y
10/29/2025, 2:25 PMfun <T> foo1(vararg elements: Iterable<T>) = /* ... */
I also have fun foo2(vararg elements: List<Bar>)
what exactly happens when I call foo1(*elements) from within foo2?
what does the spread operator do here? is this zero cost?Youssef Shoaib [MOD]
10/29/2025, 2:27 PMShow Kotlin Bytecode option in IntelliJ, but I personally just use the cfr decompiler manually.
Regardless, I believe it ends up creating a new arrayy
10/29/2025, 2:29 PMy
10/29/2025, 2:29 PMArrays.copyOf. not zero costy
10/29/2025, 2:29 PMy
10/29/2025, 2:30 PMYoussef Shoaib [MOD]
10/29/2025, 2:30 PMfoo1(elements = elements)
maybe it doesn't copy then, but I haven't checkedy
10/29/2025, 2:33 PMCLOVIS
10/30/2025, 9:29 AMclass A(
val a: Array<Int>,
)
fun A(vararg a: Int) = A(*a)
val data = arrayOf(1, 2, 3)
val a = A(*a)
data[0] = -1
println(a.contentToString())
// Without the copy:
[-1, 2, 3]
which is not what we expect at all.
And yes, in this example, the array is copied 2 times.
This is why it's highly recommended that library authors always provide an overload that accepts a List or Collection, so users can pass through lists (without copy) instead of using the spread operator.