This article explores different ways to insert an element at a given position into 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 insist on using arrays, you can use any of the following methods:

1. Using a new array

A simple solution is to create a new array with one more element to accommodate the additional element and populate it with corresponding values from the original array with the given element placed at its correct position.

Download Code

 
You can replace the for-loop with System.arraycopy() function:

Download Code

2. Using MutableList

Another solution is to convert the array into a MutableList, add the given element at its correct position in the list, and finally return an array containing all the elements in this list.

Download Code

3. Using map() function

You can also use the map() function in Kotlin like:

Download Code

That’s all about inserting an element at a given position into an array in Kotlin.