- Yair Mark
Today I was busy working through a task where I had to take one item and add it to the front of a list. I found this answer which suggested using
list.add(0, yourList);. This is cool but does not read well and it is not 100% clear what this is doing. I then remembered that Kotlin has the concept of operator overloading. All collections in Kotlin have this which means I can take code that looks like the below:
val author = "John Smith" val coolStuff = someService.coolStuff().toMutableList() coolStuff.add(0, author)
And transform this to:
val author = "John Smith" val coolStuff = listOf(author) + someService.coolStuff()
It is much clearer from the above that author is being added to the begging of the list. The only caveat is that you need to add 2 lists together to concatenate. But the other big advantage with this approach is we can stick to immutable lists and avoid making mutable lists to add to the list like in the first approach.