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>>
}

推荐答案

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())
}

Kotlin相关问答推荐

用普通Kotlin理解Gradle的Kotlin DSL'""

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

jOOQ Kotlin Coroutines - Select all and exists查询

为什么Kotlin有次构造函数和init块?

可以在没有导入声明的情况下调用 Kotlin 扩展函数吗?

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

使用事务时未调用 Kafka ConsumerInterceptor onCommit

在子类中覆盖 kotlin 运算符扩展函数

Kotlin SAM/功能接口抛出 AbstractMethodError

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

嵌套数组 indexOf()

jetpack compose 将参数传递给 viewModel

在 Kotlin 中取最后 n 个元素

从 Spring WebFlux 返回 Flux 返回一个字符串而不是 JSON 中的字符串数组

如何在Kotlin中获得KType?

Kotlin数据类打包

如何将vararg作为数组传递给Kotlin中的函数?

导航架构组件 - 未生成 DestinationFragmentArgs

将字符串转换为HashMap的最简单方法