Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<String>() vs arrayListOf<String>()

I was going through some Kotlin basics and found two syntaxes.

ArrayList<String>()

And

arrayListOf<String>()

What is the difference between these two as both are part of Kotlin.Collections?

like image 1000
Aanal Mehta Avatar asked May 16 '19 10:05

Aanal Mehta


1 Answers

arrayListOf<T>() is mainly there for your convenience. vararg-functions usually come with a (sometimes negligible) performance impact and switching between the arrayListOf(someElements...) and arrayListOf() without that convenience method would basically delegate that problem to you as a programmer. You have to know it and you would have to change that code to ArrayList(), if such an impact is affecting you and if that convenience function wouldn't exist.

arrayListOf() is basically just that. It returns ArrayList() and it is inlined. That's just convenient, so that you don't really have to think about it, when you switch back and forth between arrayListOf(someElements) and arrayListOf().

That having said: there is no difference between arrayListOf() and ArrayList() as also others have already mentioned and arrayListOf(elements) is the convenience variant to construct an ArrayList with the given elements.

like image 129
Roland Avatar answered Sep 28 '22 01:09

Roland