Today I learned:
fun foo(args: IntArray) {
val a = intArrayOf(*args) // Creates a copy of args
//val b = intArrayOf(args) // Compile error
val c = intArrayOf(elements = args)
}
To pass an array to a varargs parameter, we are supposed to use the spread operator
*
. But that creates a copy of the array, which you might not want to do if you are calling a pure function in a loop. You can't pass the array itself, but I learned that you
can pass it if you use a named parameter! Where in the documentation does it say that?
[Update: looking at the generated bytecode, the call
intArrayOf(elements = args)
also copies the array, and produces the same bytecode as using the spread operator.]