https://kotlinlang.org logo
#getting-started
Title
# getting-started
b

Ben Edwards

08/23/2022, 2:30 PM
ArrayList or mutanleListOf. Strikes me latter is better. My understanding is Arraylist specifically uses the Java implementation while mutanleListOf does not specifically use it, it tells kotlin to decide. Although if you are using JVM it will (currently) use the Java class if you are not using JVM (i.e. you are maybe doing iOS implementation) it would choose the appropriate class. So if I was planning on going to KMM in the future ArrayList would have to be changed to mutanleListOf? Would ArrrayList be preferable ever?
🚫 1
j

Joffrey

08/23/2022, 2:32 PM
Usually if you don't specifically need
ArrayList
, you should stick to the more general
mutableListOf
and let Kotlin decide, as you said, KMM or not. Note that
ArrayList
is defined in common Kotlin code, so it would be available in KMM too anyway, but that's not really the point of using
mutableListOf
- it's more about generality
👃 1
m

mkrussel

08/23/2022, 2:32 PM
The only time I would use it is when interacting with a poor third party API that requires ArrayList for the types of parameters.
I’ve dealt with APIs that required Vectors, not sure if I’ve ever encountered ArrayList requirements.
e

ephemient

08/23/2022, 2:34 PM
ArrayList has a method to explicitly reserve space for additional elements
there are a few cases where I can imagine that being useful
for everything else… just use mutableListOf
k

Klitos Kyriacou

08/23/2022, 2:37 PM
I use
ArrayList
if I know the initial capacity.
j

Joffrey

08/23/2022, 2:40 PM
In most cases where I know the initial capacity, I can usually build the target list out of a
map
operation or other functional operators, so I still don't need
ArrayList
. I haven't needed it directly for quite some time to be frank. That said, I also haven't needed
mutableListOf
much either.
buildList { ... }
usually covers everything that cannot be more efficiently expressed by functional operators
b

Ben Edwards

08/23/2022, 2:40 PM
Thanks, everybody.
k

Klitos Kyriacou

08/23/2022, 2:49 PM
And
buildList
also allows you to add an initial capacity too.
2 Views