Using Kotlin's MutableList or ArrayList where lists are needed in Android

Mike Williamson picture Mike Williamson · Nov 9, 2018 · Viewed 13.8k times · Source

I am trying to learn the "Kotlin native way" to do things in Android, while being an expert in neither Kotlin, Java, nor Android development. Specifically, when to use ArrayList versus MutableList.

It seems to me that MutableList should be chosen whenever possible. Yet, if I look at Android examples, they seem to always choose the ArrayList (as far as I've found so far).

Below is a snippet of a working example that uses ArrayList and extends Java's RecyclerView.Adapter.

class PersonListAdapter(private val list: ArrayList<Person>,
                        private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {

Question 1)

Could I simply write the above code as follows (note MutableList<> instead of ArrayList<>), even though I am borrowing from Android's Java code?

class PersonListAdapter(private val list: MutableList<Person>,
                        private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {

Question 2)

Is it really better to always use MutableList over ArrayList? What are the main reasons? Some of that link I provide above goes over my head, but it seems to me that MutableList is a looser implementation that is more capable of changing and improving in the future. Is that right?

Answer

TheWanderer picture TheWanderer · Nov 9, 2018

ArrayList is an implementation of the MutableList interface in Kotlin:

class ArrayList<E> : MutableList<E>, RandomAccess

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html

That answer may indicate that MutableList should be chosen whenever possible, but ArrayList is a MutableList. So if you're already using ArrayList, there's really no reason to use MutableList instead, especially since you can't actually directly create an instance of it (MutableList is an interface, not a class).

In fact, if you look at the mutableListOf() Kotlin extension method:

public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()

you can see that it just returns an ArrayList of the elements you supplied.