Colton Idle
12/17/2022, 5:09 PMarrayListOf
and `listOf`exist? Both seem to be of Type ArrayList?Adel Ayman
12/17/2022, 5:13 PMlistOf
gives you list so it read only
But
arrayListOf
give you mutable list so you can add and delete and edit the itemsColton Idle
12/17/2022, 5:34 PMmutableListOf
needed if we have arrayListOf
?Matthew Gast
12/17/2022, 5:35 PMarrayListOf
is just there for consistency. listOf
and mutableListOf
should be preferred unless there is a specific data structure you need.Joffrey
12/17/2022, 7:10 PMarrayListOf
if you have a specific need for an ArrayList
. Most of the time, a general mutable list should be sufficient and thus most of the time you should only need mutableListOf
Joffrey
12/17/2022, 7:11 PMList
around, or MutableList
if you really need the mutability, but you should almost never need to pass an ArrayList
aroundSergio
12/17/2022, 11:47 PMlistOf
is a function that returns an List
implementation, by default in JVM this is ArrayList
arrayListOf
is a function that returns the explicit list implementation ArrayList
ArrayList
is just an implementation of list were the data is contiguous and mutable
By default, try to use mutableListOf
or listOf
it will allow you to pass any class that implements those interfaces (this will depend of your needs)Colton Idle
12/18/2022, 3:42 AMCasey Brooks
12/18/2022, 5:05 AMMutableList
or List
, but nothing more than that, because any more specificity unnecessarily couples your code to a specific implementation of List
which makes it difficult to use.
Furthermore, listOf()
actually does return different List subclasses based on how many elements you pass to it, which may or may not be ArrayList
. For example, listOf()
returns the internal object EmptyList
, listOf(1)
returns Collections.singletonList
, and everything else returns ArrayList
.
There’s really not a good reason to use arrayListOf()
vs listOf()
. I suspect it’s mostly there for historical reasons, because older Java code sometimes would declare function parameters, etc. as ArrayList
rather than List
. When interop-ing with that code, you can’t just cast listOf()
to ArrayList
because of how that function is optimized, so arrayListOf()
gives you a way to know you’re getting exactly an ArrayList to work with those APIs.ephemient
12/18/2022, 8:54 PMArrayList
that aren't on MutableList
, e.g. to manage capacity. so in some circumstances it may be useful, even beyond Java compatibilityKlitos Kyriacou
12/19/2022, 10:15 AMList(5) { it * 2
creates the same list as listOf(0, 2, 4, 6, 8)
and can be useful if you want to create large lists.Joffrey
12/19/2022, 10:19 AM