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?
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