This article explores different ways to remove an element at a given position from an integer array in Kotlin.

Unlike a MutableList, arrays in Kotlin are fixed-length. Therefore, an element simply cannot be removed from its position in a Kotlin array. However, there are few alternatives to accomplish this.

1. Using MutableList

The idea is to convert the array into a MutableList and then call the removeAt() function to remove the element present in the specified position. Finally, make a call to toTypedArray() or toIntArray() function to convert the collection back into an array.

Download Code

2. Using filter() with map() function

Here, the idea is to get a list of valid indices for the array, excluding the specified index from where the element needs to be removed. Then transform the indices into the corresponding element in the original array and return the collection as an array.

Download Code

3. Using System.arraycopy() function

Another idea is to create a new array having one less element than the original array. Then call the System.arraycopy() function to copy elements from the original array into the new array, with the specified element excluded.

Download Code

4. Using for loop

Instead of using System.arraycopy(), we can write our custom routine using Kotlin’s native for-loop. We can do this by creating a new array with one less element and copying the corresponding values from the original array to the new array using a for-loop.

Download Code

That’s all about removing an element at a specific index from an array in Kotlin.