1. Overview

In this tutorial, we’ll discover various ways in which we can initialize a List in Kotlin. The Kotlin Standard Library provides an implementation of the List data type. List implementation and its utility methods are defined in  Collections.kt file from the kotlin.collections package.

2. Creating an Empty Immutable List

We can create an empty immutable List using the emptyList method:

@Test
fun emptyList() {
    val emptyList = emptyList<String>()
    assertTrue(emptyList.isEmpty(), "List is empty")
}

3. Creating an Immutable List

We can use the listOf list builder for creating an immutable List. We need to specify all the elements during List creation. The listOf builder returns an instance of the List interface and hence is immutable.

Let’s see it in action:

val readOnlyList = listOf<String>("John", "Doe")

In the previous example, we specified all the elements. We can also use another list with the listOf builder to initialize a list:

val readOnlyList = listOf<String>("John", "Doe")
//using another list and spread operator
val secondList = listOf<String>(*readOnlyList.toTypedArray())

We can also use an immutable List while filtering out null values. For this, we need to use the listOfNotNull method. Let’s see a sample:

val filteredList = listOfNotNull("A", "B", null)

4. Creating a Mutable List

4.1. Using mutableListOf

We can create mutable lists using the mutableListOf List builder method. It returns an instance of the MutableList interface, which provides add, remove, and other list manipulation methods. Let’s see how we can use this method in our code:

@Test
fun readWriteList() {
    var mutableList = mutableListOf<String>()
    mutableList.add("Sydney")
    mutableList.add("Tokyo")
    assert(mutableList.get(0) == "Sydney")
    mutableList = mutableListOf("Paris", "London")
    assert(mutableList.get(0) == "Paris")
}

4.2. Using arrayListOf

We can create an instance of ArrayList by using the arrayListOf method.

ArrayList is a child of MutableList and implements the RandomAccess interface. Let’s see how we can use it:

@Test
fun readWriteList() {
    var arrList = arrayListOf<Int>()
    arrList.add(1)
    arrList.remove(1)
    assert(arrList.size == 0)
    arrList = arrayListOf(1, 2, 3, 4)
    assert(arrList.size == 4)
}

5. Converting to List

We can also convert a datatype like Map to a List. The toList extension function on Map converts its elements to a List:

@Test
fun fromMaps() {
    val userAddressMap = mapOf(
        "A" to "India",
        "B" to "Australia",
        "C" to null
    )
    val newList : List<Pair<String,String?>> = userAddressMap.toList()
    assert(newList.size == 3)
}

6. List Builders

We can create List or MutableList objects by specifying size and an initialization lambda function:

fun dynamicBuild(){
    val myList = List(10){
        it.toString()
    }
    println(myList) 
    val myMutableList = MutableList(10){
        it.toString()
    }
    myMutableList.add("11")
    println(myMutableList)
}

Let’s look at the output from the above example:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

6.1. Using buildList()

Using the buildList method allows us to define a builderAction lambda in which we can manipulate a MutableList. The buildList method then returns an instance of a read-only List with the same elements.

Let’s see how to do this with an example:

fun build(){
    val students = listOf<String>("Hertz","Jane")
    val myList = buildList<String>(students.size + 1) {
        add("Jitendra")
        addAll(students)
    }
    println(myList)
}

The previous sample produces the output:

[Jitendra, Hertz, Jane]

7. Conclusion

In this article, we saw the different ways we can define a List in Kotlin. The code samples are also available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.