What is the difference between arrayListOf and mut

2019-08-02 20:53发布

问题:

This question already has an answer here:

  • Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin 3 answers

I am trying to use collections in Kotlin and got confused between arrayListOf and mutableListOf, which one should we use and why?

回答1:

Either is fine, the only difference between calling the two is expressing your intent.

ArrayList is a concrete implementation of MutableList, and mutableListOf, as of Kotlin 1.1, also returns an ArrayList.

Do you know you specifically want an ArrayList because you have made the conscious decision that this is the right choice for your application? You probably want arrayListOf (or a direct call to the ArrayList constructor, if that interface works better for you).

Do you just want a MutableList of some sort, and are fine with getting whatever the implementation defines as the right choice? Just use mutableListOf instead.