29

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?

1
  • 3
    would be easier to use mapNotNull{} to avoid some surprises or exceptions
    – HawkPriest
    Jul 4, 2018 at 12:41

2 Answers 2

27
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

1
  • There is no need to use as MutableList here, and in some cases that will cause a crash because not all overloads of the listOf function in the standard library use MutableList under the hood.
    – Tenfour04
    Sep 15, 2022 at 14:24
6

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.