Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
commmunitycreator

How to use the removeFirst method of MutableList in Kotlin

Programming Bytes

Overview

The removeFirst method can be used to remove the first element of the MutableList.

Syntax

fun <T> MutableList<T>.removeFirst(): T

Parameter

This method doesn’t take any arguments.

Return value

This method returns the removed element.

Exception

If the MutalbeList is empty then NoSuchElementException is thrown.

Code

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") 
  
}
Using the removeFirst method to remove the first element of the MutablaList

Explanation

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

kotlin
commmunitycreator
RELATED COURSES

View all Courses

Keep Exploring