How to initialize List<T> in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

List<T> denotes a List collection of generic data type. By <T>, we understand that the List does not have any specific data type. Let's check how we can initialize such a collection in Kotlin.

List<T> can be of two types: immutable and mutable. We will see two different implementations of initializing List<T>.

Example – Initialize List<T> ~ Immutable List

Once a list is declared as Immutable, then it becomes read-only.

fun main(args: Array<String>) {
   var myImmutableList = listOf(1, 2, 3)

   // Convert array into mutableList
   // Then, add elements into it.
   myImmutableList.toMutableList().add(4)

   // myImmutableList is not a mutable List
   println("Example of Immutable list: " + myImmutableList)
}

Output

In this example, we have declared an immutable list called "myImmutableList" and we have printed the same after adding a value in it.

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

Example – Initialize List<T> ~ Mutable List

We can modify the values of a mutable list. The following example shows how to initialize a mutable list.

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

Output

It will produce the following output −

Example of mutable list: [1, 2, 3, 4]
raja
Updated on 16-Mar-2022 14:16:24

Advertisements