32

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?

1

3 Answers 3

60

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

addAttributes(*atts)

This worked.

Sign up to request clarification or add additional context in comments.

1 Comment

What about the opposite? If I have varargs of string, and I want to pass as an array of strings?
5

If you have an array then make it like:

addAttributes(*arrayVar)

If you have a list then in that case:

addAttributes(*listVar.toTypedArray())

Comments

1

you have two ways:

  1. using named parameter
    addAttributes(attributes = arrayOf("1", "2", "3"))
  2. using spread operator
    addAttributes(*arrayOf("1", "2", "3"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.