private val repositories = mutableListOf<String>()
private val repositories = ArrayList<String>()
Both are mutable list, then what is the point of two keywords mutableListOf
or ArrayList
?
or is there any major difference?
private val repositories = mutableListOf<String>()
private val repositories = ArrayList<String>()
Both are mutable list, then what is the point of two keywords mutableListOf
or ArrayList
?
or is there any major difference?
两者之间的唯一区别是传达你的意图.
When you write val a = mutableListOf()
, you're saying "I want a mutable list, and I don't particularly care about the implementation". When you write, instead, val a = ArrayList()
, you're saying "I specifically want an ArrayList
".
实际上,在Kotlin编译到JVM的当前实现中,调用mutableListOf
将生成ArrayList
,行为上没有区别:一旦建立了列表,所有东西的行为都将相同.
Now, let's say that a future version of Kotlin changes mutableListOf
to return a different type of list.
更有可能的是,Kotlin团队只有在他们认为新的实现更适合大多数用例的情况下才会做出改变.mutableListOf
将让您透明地使用新的列表实现,您将免费获得更好的行为.如果听起来像你的案子,那就选mutableListOf
吧.
On the other hand, maybe you spent a bunch of time thinking about your problem, and figured that ArrayList
really is the best fit for your problem, and you don't want to risk getting moved to something sub-optimal. Then you probably want to either use ArrayList
directly, or use the arrayListOf
factory function (an ArrayList
-specific analogue to mutableListOf
).