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?
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.
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.
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.
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.
I used the spread operator that basically spreads the elements to make them compatible with varargs
.
addAttributes(*atts)
This worked.
If you have an array then make it like:
addAttributes(*arrayVar)
If you have a list then in that case:
addAttributes(*listVar.toTypedArray())
you have two ways:
addAttributes(attributes = arrayOf("1", "2", "3"))
addAttributes(*arrayOf("1", "2", "3"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With