ArrayList or mutanleListOf. Strikes me latter is ...
# getting-started
b
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
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
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
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
I use
ArrayList
if I know the initial capacity.
j
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
Thanks, everybody.
k
And
buildList
also allows you to add an initial capacity too.