Authors Top

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

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.

Authors Bottom

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!