[英]Compile time error in passing vararg parameter to another function in Kotlin
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. 我试图接受一个vararg参数作为Kotlin中的函数参数,并尝试将其传递给另一个带有vararg参数的函数。 However, it gives me a compile time error in doing so, type mismatch: inferred type is IntArray but Int was expected
. 但是,这样做会给我一个编译时错误, 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中尝试相同的代码,它的工作原理。
Java: 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), ie 只需在你传递的参数(扩展运算符)前放一个*
,即
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 另请参阅: Kotlin函数参考#varargs
The parameter a
inside function a()
has type IntArray
and needs to be converted to varargs
again when passed to b
. 该参数a
内部函数a()
的类型为IntArray
和需要被转换到varargs
传递给时再次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 之前在这里有更详细的描述: https : //stackoverflow.com/a/45855062/8073652
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.