Is it possible to use a collection as varargs?


#1

Is it possible to pass in a collection (e.g. a list) into a function which takes varargs?

Here is my example code which doesn’t compile:

data class Parameter(val name: String, val required: Boolean)

fun mapByName(params: List<Parameter>): Map<String, Parameter> {
  val pairs = params.map { param -> Pair(param.name, param) }
  val mappedPairs = mapOf(pairs)
  return mappedPairs
}

The error I get is:

Error:(15, 35) Kotlin: Too many arguments for public fun <K, V> mapOf(): kotlin.Map<K, V> defined in kotlin


#2

You can use pairs.toMap() instead:

  val x = listOf(1,2,3)
  val pairs = x.map { it to it.toString()}
  val map = pairs.toMap()


#3

Or even

fun mapByName(params: List<Parameter>): Map<String, Parameter> = params.toMap { it.name }

in your specific case.


#4

Tidy! Thanks very much.

This is my first venture into programming in Kotlin - so far I have to say I’m loving it!