How does one pass an Array<Int> to a vararg Int function using the Spread Operator?
Basically, Array<Int>
is an array of boxed Integer
objects under the hood, while IntArray
translates to an array of primitive int
values (see this answer).
To pass in an Array<Int>
to a vararg function, you can use the toIntArray()
function to convert it to an IntArray
first:
val numbers: Array<Int> = arrayOf(1, 2, 3)printNumbers(*numbers.toIntArray())
Or if you can, create the array as an IntArray
to begin with - this way you avoid the allocation of an extra array in the process, as well as the boxing of each individual value:
val numbers: IntArray = intArrayOf(1, 2, 3)printNumbers(*numbers)
The problem is that you're using the boxed Integer
s when creating an Array<Int>
. This does not work well with vararg Int
. It works with an IntArray
though:
val numbers: Array<Int> = arrayOf(1, 2, 3)printNumbers(*numbers.toIntArray())
Or directly create the array with the correct type:
val numbers = intArrayOf(1, 2, 3)printNumbers(*numbers)
Using an IntArray
, as opposed to Array<Int>
, removes the boxing overhead, which surely is preferable.