https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Klitos Kyriacou

02/28/2022, 3:11 PM
Today I learned:
Copy code
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.]
😲 2
y

Youssef Shoaib [MOD]

02/28/2022, 4:11 PM
I'm guessing that passing it using a named parameter specifies the intent that you would like to treat the parameter as an array instead of a varargs parameter. I think the only reason that this is a thing is to prevent ambiguity where in certain generic situations an array could either be meant as a singular argument to a varargs parameter or it could be meant as a replacement for the varargs parameter
In other words, think of the difference between:
Copy code
fun 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
}
2 Views