The removeFirst
method can be used to remove the first element of the MutableList
.
fun <T> MutableList<T>.removeFirst(): T
This method doesn’t take any arguments.
This method returns the removed element.
If the MutalbeList
is empty then NoSuchElementException
is thrown.
The code below demonstrates how to use the removeFirst
method:
fun main() { // create a new MutableList of int elements. var list = mutableListOf(1, 2, 3, 4) println("The list is $list") val removed = list.removeFirst(); println("\nThe removed element is $removed") println("\nNow the list is $list") }
In the code above,
Line 3: We create a new MutableList
object with name list
using the mutableListOf()
method. For the mutableListOf()
method we provide 1,2,3,4
as an argument. All the provided arguments are present in the returned list
. The list is [1,2,3,4]
.
Line 6: We use the removeFirst
method to remove the first element from the list. The removeFirst
method removes the element 1
from the list [1,2,3,4]
and
returns it. Now the list is [2,3,4]
.
RELATED TAGS
CONTRIBUTOR
View all Courses