How to pass <Int> array to vararg Int function using Spread statement?

I have a vararg function that takes multiple Ints. I have Array<Int>one that I would like to use as input.

Unsuccessful attempt:

Here is my attempt to call a 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 get the following type mismatch error:

error: type mismatch: inferred type is Array<Int> but IntArray was expected
printNumbers(*arrayOf<Int>(1, 2, 3))
              ^

Additional confusion:

I do not understand why I get this error, especially since I can use the spread operator on Array<String>. For instance...

fun printStrings(vararg strings: String) {
    strings.forEach { it -> println(it) }
}

val strings: Array<String> = arrayOf("hello", "there", "stackoverflow")
printStrings(*strings)

Conclusion:

hello
there
stackoverflow

Attempts to fix the error:

  • , , Array<Int> IntArray, . , (IntArray to Array<Int>)

  • arrayOf. . arrayOf<Int>(1, 2, 3). ( ) .

:

  • Kotlin 1.0.3

  • , , Array<Int> IntArray .


Array<Int> vararg, Int s?

+4
2

, Array<Int> Integer , IntArray int (. ).

Array<Int> vararg, toIntArray(), IntArray:

val numbers: Array<Int> = arrayOf(1, 2, 3)
printNumbers(*numbers.toIntArray())

, , IntArray - , :

val numbers: IntArray = intArrayOf(1, 2, 3)
printNumbers(*numbers)
+7

, Array<Int> Integer. vararg Int. IntArray, :

val numbers: Array<Int> = arrayOf(1, 2, 3)
printNumbers(*numbers.toIntArray())

:

val numbers = intArrayOf(1, 2, 3)
printNumbers(*numbers)

IntArray, Array<Int>, , , , .

+3

Source: https://habr.com/ru/post/1693803/


All Articles