This article explores different ways to add an item at the end of a mutable list in Kotlin.

1. Using add() function

A simple solution to add elements to a list is using the add() function. It is available only for a mutable list and can be used as follows to add an item at the end of a list:

Download Code

 
The add() function optionally takes the index where the specified element needs to be inserted. To insert an item at the end, use the index equal to the list’s size.

Download Code

2. Using addAll() function

To append multiple items to the end of a list, use the addAll() function which accepts a collection. A typical invocation for this function would look like:

Download Code

3. Using Deque

We can insert an item at the end (and at the front) of a Deque in constant time. Any standard Deque implementation functionality to add the specified element at the end of a Deque. In Kotlin, we have the addLast() function.

Download Code

4. Using + operator

The idiomatic way to add an item at the end of a list is using the + operator. To illustrate, the following code creates a new list, which is the concatenation of the original list with a single item or a collection. We can use the plus() function as well.

Download Code

That’s all about adding an item at the end of a list in Kotlin.