What is the mutableListOf method in Kotlin?

Overview

In Kotlin, the mutableListOf method is used to create a MutableList, which is a collection of elements that supports adding and removing elements. Using this method, we can:

  1. Create an empty MutableList.
  2. Create a MutableList with elements.

Syntax

// empty MutableList
fun <T> mutableListOf(): MutableList<T>

Parameters

This method takes no parameters.

Return value

It returns an empty MutableList object.

Syntax to create MutableList with elements

// MutableList with elements
fun <T> mutableListOf(vararg elements: T): MutableList<T>

Parameters

The parameters for this method are the elements to be included in the MutableList.

Return value

It returns a MutableList object with the provided arguments as elements.

Example

fun main() {
val mutableList1 = mutableListOf<Int>()
println("mutableList1 : $mutableList1");
val mutableList2 = mutableListOf(1,2,3,4,5);
println("mutableList2 : $mutableList2");
}

Explanation

  • Line 2: We use the mutableListOf method to create an empty MutableList object. This object can have Int type values as elements.

  • Line 5: We use the mutableListOf method to create a MutableList object with five Int values 1,2,3,4,5. This method returns a MutableList object with the provided arguments as elements.

Free Resources