Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an Array to varargs parameter

Tags:

kotlin

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?

like image 916
Ammar Avatar asked Oct 19 '17 01:10

Ammar


People also ask

Can you pass an array to Varargs?

If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

Can you pass a list to Varargs Java?

Passing an ArrayList to method expecting vararg as parameter To do this we need to convert our ArrayList to an Array and then pass it to method expecting vararg. We can do this in single line i.e. * elements passed. // function accepting varargs.

Can we pass array as argument in Java?

Java For Testers You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.

How do you pass an array to a value in Java?

To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.


3 Answers

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

addAttributes(*atts) 

This worked.

like image 190
Ammar Avatar answered Sep 20 '22 02:09

Ammar


If you have an array then make it like:

addAttributes(*arrayVar)

If you have a list then in that case:

addAttributes(*listVar.toTypedArray())
like image 42
Ali Nawaz Avatar answered Sep 21 '22 02:09

Ali Nawaz


you have two ways:

  1. using named parameter
    addAttributes(attributes = arrayOf("1", "2", "3"))
  2. using spread operator
    addAttributes(*arrayOf("1", "2", "3"))
like image 24
amirhossein p Avatar answered Sep 19 '22 02:09

amirhossein p