3

I'm trying to accept a vararg parameter as a function parameter in Kotlin and trying to pass it to another function with vararg parameters. However, it gives me a compile time error in doing so, type mismatch: inferred type is IntArray but Int was expected.

Kotlin:

fun a(vararg a: Int){
   b(a) // type mismatch inferred type is IntArray but Int was expected
}

fun b(vararg b: Int){

}

However, if I try the same code in Java, it works.

Java:

void a(int... a) {
    b(a); // works completely fine
}

void b(int... b) {

}

How can I get around this?

Pinaki Acharya
  • 339
  • 3
  • 11

2 Answers2

5

Just put a * in front of your passed argument (spread operator), i.e.

fun a(vararg a: Int){
  // a actually now is of type IntArray
  b(*a) // this will ensure that it can be passed to a vararg method again
}

See also: Kotlin functions reference #varargs

Roland
  • 22,259
  • 4
  • 57
  • 84
1

The parameter a inside function a() has type IntArray and needs to be converted to varargs again when passed to b. This can be done with the "spread operator": *

fun a(vararg a: Int) {
    b(*a) // spread operator
}

It's been described in slightly more detail here before: https://stackoverflow.com/a/45855062/8073652

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196