I have a vararg function that takes multiple Int
s. I have an Array<Int>
that I'd like to use as input.
An unsuccessful attempt:
Here is my attempt to call the function using the Spread Operator:
fun printNumbers(vararg numbers: Int) {
numbers.forEach { it -> println(it) }
}
val numbers: Array<Int> = arrayOf(1, 2, 3)
printNumbers(*numbers)
However, I'm getting the following type mismatch error:
error: type mismatch: inferred type is Array<Int> but IntArray was expected
printNumbers(*arrayOf<Int>(1, 2, 3))
^
Extra confusion:
I don't understand why I'm getting this error, especially since I can use the spread operator on an Array<String>
. For example...
fun printStrings(vararg strings: String) {
strings.forEach { it -> println(it) }
}
val strings: Array<String> = arrayOf("hello", "there", "stackoverflow")
printStrings(*strings)
Output:
hello
there
stackoverflow
Attempts to correct the error:
I searched online to see if it was possible to convert an
Array<Int>
to anIntArray
, as this might satisfy the compiler. I couldn't see anything except the opposite conversion (IntArray
toArray<Int>
)I tried specifying the generic type when calling
arrayOf
. E.g.arrayOf<Int>(1, 2, 3)
. This (for obvious reasons) didn't work.
Notes:
I'm using Kotlin version 1.0.3
I think some of my confusion stems from the fact that I don't understand the difference between
Array<Int>
andIntArray
and when to choose one over the other.
How do I pass an Array<Int>
into a vararg function that expects multiple Int
s?