This article explores different ways to remove a value from an array in Kotlin.

Since the size of an array cannot be changed in Kotlin, we cannot remove a value from it. However, we can create a new array, and then copy all the values from the original array into the new array, except the one which we want to remove. There are several ways to do that:

1. Using filter() function

The idea is to filter the array to remove the specified value and accumulate the remaining elements into the new array using the toIntArray() function. This removes all occurences of a value from the array.

Download

Output:

[8, 2, 1, 10, 8, 9]

 
For typed arrays, you can use the toTypedArray() function:

Download

Output:

[A, D, A]

2. Using System.arraycopy() function

If you want to remove a value by its index, consider using the System.arraycopy() function for better performance. The idea is to allocate a new array of size one less than the original array. Then call the System.arraycopy() function to copy the values before and after that index into the new array.

Download

Output:

[A, B, C, D]

That’s all about removing a value from an array in Kotlin.