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:
- Create an empty
MutableList. - Create a
MutableListwith elements.
Syntax
// empty MutableListfun <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 elementsfun <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
mutableListOfmethod to create an emptyMutableListobject. This object can haveInttype values as elements. -
Line 5: We use the
mutableListOfmethod to create aMutableListobject with fiveIntvalues1,2,3,4,5. This method returns aMutableListobject with the provided arguments as elements.