1. Overview

In this quick tutorial, we’ll discuss two ways of creating mutable lists in Kotlin.

2. Creating a Mutable List in Kotlin

2.1. ArrayList<T>()

We can create an ArrayList implementation of the mutable list simply by using a constructor:

val arrayList = ArrayList<String>()
arrayList.add("Kotlin")
arrayList.add("Java")

This is Kotlin’s implementation of dynamic arrays.

2.2. mutableListOf<T>()

We can also create a mutable list by using a dedicated method:

val mutableList = mutableListOf<String>()
mutableList.add("Kotlin")
mutableList.add("Java")

Let’s peek at the current (Kotlin 1.4.10) implementation of the mutableListOf<T>() method:

/**
 * Returns an empty new [MutableList].
 * @sample samples.collections.Collections.Lists.emptyMutableList
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()

As we can see, it simply returns an instance of ArrayList<T>(), which is the default implementation of List. So the implementation details of the mutable list have been abstracted away for us.

3. Conclusion

In this quick article, we saw two ways to create a mutable list in Kotlin.

Our first approach explicitly creates an instance of a particular class by calling its constructor — ArrayList<T>().

In the second approach, we just want a mutable list and don’t really care about the implementation, and therefore, we can’t make any assumptions about the actual implementation used under-the-hood.

However, as we noted, both approaches have the same result in the current version of Kotlin, as both will create an ArrayList.

guest
0 Comments
Inline Feedbacks
View all comments