salyela
salyela

Reputation: 1645

Getting type mismatch on varargs in Kotlin

Here is my simple situation in code

fun receiveDogs(vararg dog: Dog){
    processDogs(dog)
    ... //more cool stuff
}

fun processDogs(vararg dog: Dog){
  .....//cool stuff
}

When I do this the calling of processDogs(dog) causes a compilation error of

Type mismatch.

Required: Dog

Found: Array<out Dog>

Now understand that both of my functions want a vararg. Is there a simple way to fix this?

Upvotes: 3

Views: 687

Answers (2)

Ilya E
Ilya E

Reputation: 752

According to docs:

Inside a function a vararg-parameter of type T is visible as an array of T

So your function processDogs needs to take dogs parameter as Array<out T> or you could use spread operator * on the array to pass it in vararg function.

fun processDogs(dogs: Array<Dog>)

or

processDogs(*dog)

as mentioned above. Both compiles and works fine

Upvotes: 2

Codetector
Codetector

Reputation: 774

Oh... you need to do

processDogs(*dog)

You need to spread the array into vararg again.

Upvotes: 6

Related Questions