Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convert List to vararg

Tags:

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?

like image 624
Jack Guo Avatar asked Jul 03 '18 19:07

Jack Guo


People also ask

How do you make Vararg in Kotlin?

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.

How do you pass an array as Vararg in Kotlin?

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.

What is spread operator in Kotlin?

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 *):


2 Answers

fun foo(vararg strings: String) { /*...*/ }

Using

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

like image 82
Braian Coronel Avatar answered Sep 20 '22 03:09

Braian Coronel


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).

like image 38
Alexey Romanov Avatar answered Sep 19 '22 03:09

Alexey Romanov