28

If I have a function header like:

fun addAttributes(vararg attributes: String) {
  ...
}

And I want to pass attributes in here:

val atts = arrayOf("1", "2", "3")
addAttributes(atts)

It gives a compilation error about incompatible types. What should I do?

Ammar
  • 5,070
  • 8
  • 28
  • 27
  • 4
    Possible duplicate of [How to pass a kotlin collection as varagrs?](https://stackoverflow.com/questions/46418550/how-to-pass-a-kotlin-collection-as-varagrs) – s1m0nw1 Oct 19 '17 at 04:35

3 Answers3

54

I used the spread operator that basically spreads the elements to make them compatible with varargs.

addAttributes(*atts)

This worked.

Ammar
  • 5,070
  • 8
  • 28
  • 27
4

If you have an array then make it like:

addAttributes(*arrayVar)

If you have a list then in that case:

addAttributes(*listVar.toTypedArray())
Ali Nawaz
  • 2,016
  • 20
  • 30
1

you have two ways:

  1. using named parameter
    addAttributes(attributes = arrayOf("1", "2", "3"))
  2. using spread operator
    addAttributes(*arrayOf("1", "2", "3"))
Amir Hossein
  • 392
  • 3
  • 11