Klitos Kyriacou
02/28/2022, 3:11 PMfun 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.]Youssef Shoaib [MOD]
02/28/2022, 4:11 PMfun foo(args: IntArray) {
val a = listOf(*args) // Creates a copy of args and creates a list containing the elements of args
val c = listOf(args) // Creates a list that contains the array args
}