How to add an item to an ArrayList in Kotlin?


In this example, we will see how we can define an ArrayList in Kotlin and add an item in the list. We can do it using the library function add() or we can use the "+=" operator. In order demonstrate, we will be creating two ArrayLists, one is of mutable type and the other is of immutable type.

Example – Inserting a new item using add()

We can insert an item to an ArrayList using the add() function provided by the Kotlin library. In this example, we will be creating two lists: one is "myMutableList" which is a collection of mutable data types, and the other one is "myImmutableList" which is a collection of immutable data types.

We cannot use add() directly on the immutable collection. In order to use the add() function, we need to first convert the immutable list to mutable by using the toMutableList() function and then we can apply add() in it.

fun main(args: Array<String>) {
   val myMutableList = mutableListOf(1, 2, 3)
   myMutableList.add(4)
   println("Example of mutable list: " + myMutableList)
   
   // Convert array to mutableList using toMutableList() method
   // Then, insert element into it
   var myImmutableList = listOf(1, 2, 3)
   myImmutableList.toMutableList().add(4)
   
   // myImmutableList is not a mutable List
   println("Example of Immutable list: " + myImmutableList)
}

Output

It will produce the following output −

Example of mutable list: [1, 2, 3, 4]
Example of Immutable list: [1, 2, 3]

Example – Adding an item using "+=" operator

Kotlin provides another operator "+=" to add an item into the list. This operator works on both mutable and immutable data types. We will modify the above example using "+=" operator.

fun main(args: Array<String>) {
   val myMutableList = mutableListOf(1, 2, 3)
   myMutableList += 4
   println("Example of mutable list: " + myMutableList)
   
   var myImmutableList = listOf(1, 2, 3)
   myImmutableList += 4
   println("Example of Immutable list: " + myImmutableList)
}

Output

It will produce the following output −

Example of mutable list: [1, 2, 3, 4]
Example of Immutable list: [1, 2, 3, 4]

Updated on: 16-Mar-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements