How to add an item to a list in Kotlin?

Solution 1:

A more idiomatic approach would be to use MutableList instead of specifically ArrayList. You can declare:

val listOfVehicleNames: MutableList<String> = mutableListOf()

And add to it that way. Alternatively, you may wish to prefer immutability, and declare it as:

var listOfVehicleNames: List<String> = emptyList()

And in your completion block, simply reassign it:

listOfVehicleNames = response.body()?.message()?.orEmpty()
    .map { it.name() /* assumes name() function exists */ }

Solution 2:

If you don't want or can't use array list directly use this code for add item

itemsList.toMutableList().add(item)

itemlist : list of your items

item : item you want to add

Solution 3:

Talking about an idiomatic approach... 🙄

When you can get away with only using immutable lists (which means usually in Kotlin), simply use + or plus. It returns a new list with all elements of the original list plus the newly added one:

val original = listOf("orange", "apple")
val modified = original + "lemon" // [orange, apple, lemon]

original.plus("lemon") yields the same result as original + "lemon". Slightly more verbose but might come in handy when combining several collection operations:

return getFruit()
       .plus("lemon")
       .distinct()

Besides adding a single element, you can use plus to concatenate a whole collection too:

val original = listOf("orange", "apple")
val other = listOf("banana", "strawberry")
val newList = original + other // [orange, apple, banana, strawberry]

Disclaimer: this doesn't directly answer OP's question, but I feel that in a question titled "How to add an item to a list in Kotlin?", which is a top Google hit for this topic, plus must be mentioned.

Solution 4:

instead of using a regular list which is immutable just use an arrayListof which is mutable

so your regular list will become

var listofVehicleNames = arrayListOf("list items here")

then you can use the add function

listOfVehicleNames.add("what you want to add")