Remove an item from Array in Kotlin

In this post, we are going to explain different methods that can be used to delete elements from an array using Kotlin. We will be converting the array to a mutable list to delete items from array.

fun removeElement(arr: Array<String>, itemIndex: Int): Array<String> {
    val arrList = arr.toMutableList()
    return arrList.toTypedArray()

fun main() {
	var fruits = arrayOf<String>("Apple", "Banana", "Orange", "Papaya")
    // Remove second element from array
    fruits = removeElement(fruits, 2)


[Apple, Banana, Papaya]

We have created an array called fruits that contain multiple items. We want to delete an item that has an index 2. To remove the item we have created a function named 'removeElement'. In this function, we are taking two parameters. First is the array from where you want to delete the item. The second is the index of the item that needs to be removed. 

We are converting the array to a mutable list using the .toMutableList() function and using removeAt() function of the mutable list, we are removing the item.

Remove an item from Mutable List in Kotlin

If we have a mutable list then we can easily remove the item from it. The mutable list has a function removeAt() that takes the index as a parameter and removes that item from the Mutable List.



Code example

fun main() {
    val mList = mutableListOf<Int>(10, 20, 30, 40, 50, 60)


[10, 20, 30, 50, 60]
Was this helpful?