Why use MutableList<T> instead of ArrayList&...
# getting-started
j
Why use MutableList<T> instead of ArrayList<T> in Kotlin? What was the idea standing behind the creation of that class in Kotlin when mostly the rest of the collections are used as declared in Java? If you have any docs/articles that might help me understand it, it would be very helpful. Thanks 👋🏼
r
In Java the
List
interface implies mutability - it has
add
and
remove
etc. methods. If you make an immutable List implementation you have to keep all of those methods and make them throw
UnsupportedOperationException
. In Kotlin
List
does not have those methods, they are only added in
MutableList
. Which is much better - you have to explicitly type for mutability, and if a method returns
List
rather than
MutableList
you know you are not intended to mutate it.
ArrayList
in Kotlin, as in Java, is a particular way of implementing a List (mutable or otherwise)- via a backing memory array. You can also implement it as a
LinkedList
, or in other ways.
👍🏼 1
More generally, code should know as little as practical about the objects it interacts with, so it should treat them as the highest type that provides all the functionality it needs. Code to interfaces, not implementations. There are multiple ways of implementing a mutable list, of which
ArrayList
is only one. 99% of the time code operating on a
MutableList
should not care how it was implemented, so unless there’s some very, very good reason you should type your mutable lists as
MutableList
rather than
ArrayList
. (And if you can type it as a
List
and not mutate it at all, so much the better.)
👍 1
👍🏼 1
i
Interesting how ArrayList extends MutableList
by According to https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/ , MutableList is actually interface.
k
MutableList is indeed an interface, but there is also a standalone function with the same name. So when you write
val x = MutableList<String>(10) { it.toString() }
, although it looks as if you're calling a constructor, you are in fact calling a standalone function MutableList which returns a MutableList object implemented as an ArrayList. The interface
MutableList
is indeed preferred to be used as an argument rather than
ArrayList
. If you want to distinguish between ArrayList and LinkedList, for example, to use a better performing algorithm when you know that the list features fast random access, you can use the fact that such a list may implement the
RandomAccess
marker interface.