Kotlin Collections

Adding Elements to Lists in Kotlin

Spread the love

Kotlin offers flexible ways to manage collections, but understanding the difference between mutable and immutable lists is crucial. This article explores adding elements to both types using add() and the += operator.

Table of Contents

Adding Elements with the add() Function

The add() function provides versatile ways to add elements to an ArrayList. You can append to the end or insert at a specific index.

Appending to the end:


val mutableList = ArrayList()
mutableList.add("Apple")
mutableList.add("Banana")
mutableList.add("Cherry")

println(mutableList) // Output: [Apple, Banana, Cherry]

Inserting at a specific index:


mutableList.add(1, "Orange") // Adds "Orange" at index 1
println(mutableList) // Output: [Apple, Orange, Banana, Cherry]

Adding Elements with the += Operator

The += operator offers a concise way to add elements, particularly useful for appending single elements or merging lists.

Adding a single element:


val mutableList2 = ArrayList()
mutableList2 += 1
mutableList2 += 2
mutableList2 += 3

println(mutableList2) // Output: [1, 2, 3]

Adding multiple elements from another collection:


val list1 = ArrayList(listOf(1,2,3))
val list2 = listOf(4,5,6)
list1 += list2

println(list1) // Output: [1, 2, 3, 4, 5, 6]

Working with Immutable Lists

Both add() and += are designed for mutable lists. Attempting to use them on an immutable list (created using listOf()) will result in a compile-time error. To add to an immutable list, you must create a new list containing the original elements and the new ones.


val immutableList = listOf("Apple", "Banana", "Cherry")
val newList = immutableList + "Orange" //Creates a new list
println(newList) // Output: [Apple, Banana, Cherry, Orange]

In Summary:

add() provides granular control, while += offers concise syntax. Choose the method that best suits your needs. Always remember the distinction between mutable and immutable lists to avoid errors.

Leave a Reply

Your email address will not be published. Required fields are marked *