Jakub Aniola
10/17/2021, 12:37 PMRob Elliot
10/17/2021, 1:09 PMList 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.Rob Elliot
10/17/2021, 1:15 PMArrayList 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.)itnoles
10/18/2021, 4:28 AMitnoles
10/18/2021, 4:30 AMKlitos Kyriacou
10/18/2021, 9:02 AMval 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.