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

Jérémy CROS

09/02/2021, 9:45 AM
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

Javier

09/02/2021, 9:56 AM
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

Klitos Kyriacou

09/02/2021, 11:15 AM
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

Jérémy CROS

09/02/2021, 12:07 PM
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

Michael Böiers

09/03/2021, 11:30 AM
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
2 Views