I have input data of type List<UnitWithComponents>
class UnitWithComponents {
var unit: Unit? = null
var components: List<Component> = ArrayList()
}
I want to convert the data to a vararg
of Unit
Currently I am doing *data.map { it.unit!! }.toTypedArray()
. Is there a better way to do it?
Variable number of arguments (varargs)Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.
There are multiple ways of converting a Kotlin array to a vararg parameter. Firstly, we can simply pass an array with a spread operator to the function call. It's also possible to pass multiple arrays. Additionally, we can even combine literals and arrays to functions with vararg parameters.
The * operator is known as the Spread Operator in Kotlin. From the Kotlin Reference... When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):
fun foo(vararg strings: String) { /*...*/ }
foo(strings = arrayOf("a", "b", "c"))
val list: MutableList<String> = listOf("a", "b", "c") as MutableList<String>
foo(strings = list.map { it }.toTypedArray())
Named arguments are not allowed for non-Kotlin functions (*.java)
So, in this case you should replace:
From: strings = list.map { it }.toTypedArray()
To: *list.map { it }.toTypedArray()
GL
Source
No, that's the correct way to do it (assuming you want to throw an exception when it.unit
is null
for some element of the list).
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