Search code examples
kotlinvariadic-functions

How to pass vararg as array to function in Kotlin?


I want to pass vararg from the buy function to the drive function but I get

a compile error:

required Array<T> found Array<out T>

code:

class Car

fun buy(vararg cars: Car) {
    drive(cars) //compile error
}

fun drive(cars: Array<Car>) {
    //...
}

Solution

  • 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.