https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

jean

03/18/2023, 3:56 PM
Any reason for not having something like this in the standard library?
Copy code
private fun <T> MutableList<T>.addAll(vararg element: T) = element.forEach { add(it) }
It’s only possible to pass a collection, an array, an iterable or a sequence as far as I can see. Which is not idealistic when I want to do something like this
Copy code
val list = MutableList<Int>()
when {
  someReason() -> list.addAll(1, 2, 3)
  someOtherReason() -> list.addAll(4, 5, 6)
}
e

ephemient

03/18/2023, 5:17 PM
Jean, that extension leads to
Copy code
val listOfLists = mutableListOf<List<*>>()
listOfLists.addAll()
listOfLists.addAll(emptyList())
listOfLists.addAll(emptyList(), emptyList())
behaving inconsistently
also varargs are just actually passed as arrays, so your extension is really the same function as the existing
MutableCollection<T>.addAll(elements: Array<T>)
, just with different syntax
Copy code
list.addAll(arrayOf(1, 2, 3))
list.addAll(arrayOf(4, 5, 6))
after https://youtrack.jetbrains.com/issue/KT-43871 you should be able to write
Copy code
list.addAll([1, 2, 3])
list.addAll([4, 5, 6])
j

jean

03/19/2023, 7:25 PM
I just wanted to avoid having to wrap my actual values
Copy code
list.addAll(
    [
        SomeValue.builder()
          ...
        .build(),
        ...
    ]
)
e

ephemient

03/20/2023, 7:15 PM
if that's what you're doing, I don't see what you're getting out of
addAll
as opposed to
Copy code
list.add(SomeValue.builder()....build())
list.add(...)
3 Views