Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vararg to list?

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>>
}
like image 832
Terry Avatar asked Oct 16 '19 11:10

Terry


2 Answers

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())
}
like image 74
Louis Wasserman Avatar answered Sep 30 '22 07:09

Louis Wasserman


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

fun insertMissingEntities(vararg entities: Entity) {
  val list = listOf(*entities)
  passMissingEntities(list)
}
like image 42
Terry Avatar answered Sep 30 '22 08:09

Terry