What is the minusElement method in Kotlin?

Overview

In Kotlin, the minusElement method is used to remove the first occurrence of the given element from the MutableList class, and return other elements as a new MutableList.

Syntax

fun <T> Iterable<T>.minusElement(element: T): List<T>

Parameters

This method takes the first occurrence of the element to be removed from the list as an argument.

Return value

This method returns a new MutableList object created from the invoking MutableList.

Example

fun main() {
val list: List<Int> = mutableListOf(1, 2, 3, 2, 4)
println("The list is : $list")
val newList = list.minusElement(2);
println("After removing the 1st occurrence of 2 the list is : $newList")
}

Explanation

Line 3: We use the mutableListOf method to create a new MutableList object with the name list. For the mutableListOf method, we provide 1,2,3,2,4 as an argument. All the provided arguments will be present in the returned list. The list is [1,2,3,2,4].

Line 6: We use the minusElement method with 2 as an argument. This removes the first occurrence of 2 from the list, and returns a new MutableList object. It returns [1,3,2,4].

Free Resources