本文介绍了如何将vararg作为数组传递给Kotlin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将vararg从buy函数传递给drive函数但我得到
I want to pass vararg from the buy function to the drive functionbut I get
编译错误:
required Array<T> found Array<out T>
代码:
class Car
fun buy(vararg cars: Car) {
drive(cars) //compile error
}
fun drive(cars: Array<Car>) {
//...
}
推荐答案
另一种解决方案是将drive
更改为fun drive(Array<out Car>) { ... }
.当然,这意味着无法修改驱动器内的汽车,但避免了复制.
Another solution would be to change drive
to fun drive(Array<out Car>) { ... }
. This of course means that the cars inside drive cannot be modified but avoids the copying.
这篇关于如何将vararg作为数组传递给Kotlin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!