Kotlin mutableListOf

In this guide, we will learn about the Kotlin mutableListOf() function with lots of examples.

What is mutableListOf()? 

The mutableListOf() function in Kotlin is a utility function that allows you to create a mutable list. As opposed to the read-only lists created using listOf(), mutable lists can be modified after their creation, allowing elements to be added, removed, or updated. 

Basic Syntax:

val mutableList: MutableList<Type> = mutableListOf(element1, element2, element3, ...)

Examples with Outputs

Creating a Basic Mutable List of Integers

val numbers = mutableListOf(1, 2, 3)
println(numbers)  // Output: [1, 2, 3]

Adding Elements to the List

val animals = mutableListOf("Dog", "Cat")
animals.add("Bird")
println(animals)  // Output: [Dog, Cat, Bird]

Removing Elements from the List

val colors = mutableListOf("Red", "Blue", "Green")
colors.remove("Blue")
println(colors)  // Output: [Red, Green]

Modifying Elements in the List

val fruits = mutableListOf("Apple", "Banana", "Cherry")
fruits[1] = "Mango"
println(fruits)  // Output: [Apple, Mango, Cherry]

Merging Two Mutable Lists

val list1 = mutableListOf(1, 2, 3)
val list2 = mutableListOf(4, 5, 6)
list1.addAll(list2)
println(list1)  // Output: [1, 2, 3, 4, 5, 6]

Clearing All Elements from the List

val data = mutableListOf("A", "B", "C")
data.clear()
println(data)  // Output: []

Convert a mutableListOf() to an immutable list and vice versa

val mutableList = mutableListOf(1, 2, 3)
val immutableList = mutableList.toList()
val backToMutable = immutableList.toMutableList()

Conclusion

In Kotlin, mutableListOf() is a standard library function that provides a dynamic way to create lists whose elements can be altered – you can add, remove, or modify elements as per your requirements.

Related Kotlin Posts

Comments