This article explores different ways to add a new element at the end of an array in Kotlin.

The arrays in Kotlin are fixed-size. That means once created, we can’t resize them. To get a resizable-array implementation, consider using MutableList instead, which can grow or shrink automatically as needed.

However, if you’re stuck on using arrays, you can create a new array to accommodate the additional element. We can do this in several ways:

1. Using plus() function

A good and concise solution to add an element at the end of an array in Kotlin is with the + operator or the plus() function. We can use this as:

Download Code

2. Using MutableList

The trick is to convert the array into a MutableList, add the specified element at the end of the list, and finally return an array containing all the elements in this list.

Download Code

3. Using System.arraycopy()

Another idea is to allocate the larger array for accommodating the new element(s). The following solution allocates memory for the new array, one more than the original array’s size. Then it calls the System.arraycopy() function to copy elements from the original array into the new array and finally assign the specified element to the last index of the array.

Download Code

4. Using Arrays.copyOf()

Instead of using System.arraycopy(), you can also use the copyOf() function, as shown below:

Download Code

That’s all about adding a new element at the end of an array in Kotlin.