20

I have a function with a vararg parameter. This vararg parameter needs to be passed to another function as a list.

How do I convert the vararg param into a list? listOf() gave me an error.

fun insertMissingEntities(vararg entities: Entity) {
  val list = listOf(entities)
  passMissingEntities(list) // Type mismatch. 
                            // Required: List<Entity>
                            // Found: List<Array<out Entity>>
}
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Terry
  • 14,529
  • 13
  • 63
  • 88

3 Answers3

26

You can use the extension function .asList(), which does no added copying (unlike listOf with the spread operator).

fun insertMissingEntities(vararg entities: Entity) {
  passMissingEntities(entities.asList())
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
7

The vararg param needs to be spread with the spread * operator.

fun insertMissingEntities(vararg entities: Entity) {
  val list = listOf(*entities)
  passMissingEntities(list)
}
Terry
  • 14,529
  • 13
  • 63
  • 88
0

Koltin (varang a:Entity) ~= Java (a:Entity ... a)

Which means the you can pass multiple params of type Entity not the entire array/list

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator . (prefix the array with *):

    fun insertMissingEntities(vararg entities: Entity) {
      val list = listOf(entities)  // Here entities is already a list of entity so you are doing listOf(listOf(entity)).. Hence , the error

//passMissingEntities(list) -> WRONG// Type mismatch. 
                                    // Required: List<Entity>
                                    // Found: List<Array<out Entity>>


 passMissingEntities(entities) // Just pass the entities instead of converting it to list again
    }

Also read : https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs

ArpitA
  • 721
  • 7
  • 17