Hi guys :slightly_smiling_face: What would be the ...
# getting-started
j
Hi guys 🙂 What would be the most idiomatic way to add 2 elements to a list, one at the beginning and one at the end? So far I have
listOf(element0) + listOfElements + elementLast
But I’m not sure if there are more efficient / maybe clearer options available ?
j
I like
buildList
Copy code
val list = buildList {
    add(element0)
    addAll(elements)
    add(elementLast)
}
Copy code
val list = buildList {
    add(index = 0, element = element0)
    addAll(elements)
    add(index = count(), element = elementLast)
}
That is more explicit
👍🏻 1
👍 5
k
Do you mean you want to add these two elements to an existing mutable list, or create a new list from the original and the two elements?
j
Second option 🙂 But I very much like @Javier’s proposition, did not know about it, it’s cleaner than what I was doing. Thanks! 🙂
🙂 1
m
Isn’t buildList experimental? It’s not much more complex to do it “manually” 🙂
Copy code
val listA = listOf("b", "c", "d")
val list = mutableListOf<String>().apply {
    add("a")
    addAll(listA)
    add("e")
}
🙌 1