Add item in Mutable list at 0 position without overwriting the first element

Viewed 3809

I am a Kotlin beginner. I have a mutable list which have some items, I want to add one new item to 0th index, but my list have already an item at 0th position which I want to move to 1st index. Right now my code is adding the item but the previous item is getting lost.

var list :MutableList<Food> = mutableListOf()
list.set(0,setItem)

fun setItem: Food{
    val food = Foood("Select", -1, "Dessert", "" )
    return food
}
2 Answers

The add method will not overwrite existing values, but shift them over instead:

val list: MutableList<String> = mutableListOf("one", "two", "three")
list.add(0, "zero")
println(list) // [zero, one, two, three]

You can use the .add(index, data) operator to insert.

Related