Element removal in Kotlin mutable lists

Kotlin @ Freshers.in

Kotlin doesn’t have a built-in type specifically called “array” that supports removal of elements, as arrays (Array<T>) in Kotlin have a fixed size once instantiated. However, you can use a mutable list (MutableList<T>) for a similar purpose with dynamic sizing. Below is an example of how you can initialize a mutable list, remove an element from it, and then print the results for verification.

fun main() {
    // Initialize a mutable list
    val numbers = mutableListOf(1, 2, 3, 4, 5)
    // Print the original list
    println("Original List: $numbers")
    // Remove the element at index 2 (third element, which is '3')
    numbers.removeAt(2)
    // Remove the first occurrence of the element '4'
    numbers.remove(4)
    // Print the list after removals
    println("Updated List: $numbers")
}

In this script:

  • We create a MutableList of integers with initial elements 1 through 5.
  • We print this original list to the console.
  • We remove the element at index 2 (the integer 3, since indexing starts at 0) using the removeAt function.
  • We remove the first occurrence of the integer 4 using the remove function.
  • Finally, we print out the updated list.

When you run this program, you should see the original list and the updated list after the removals in your console output.

Remember, the remove function will only remove the first occurrence of the specified element, and the removeAt function will remove the element at the specified index. If the element or index doesn’t exist, it will not change the list or may throw an IndexOutOfBoundsException, respectively.

Author: user