Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using listOf vs arrayListOf

Tags:

kotlin

Is there any best practice as for using listOf() or arrayListOf() in Kotlin code? They both actually returns the same implementation and I understand listOf is better in the sense that it is not tied to specific implementation. Here are the docs for it?
Is it documented anywhere in the language style?
Are there any other reasons to use each one?

like image 654
oshai Avatar asked Dec 17 '22 14:12

oshai


1 Answers

One notable and important difference is that listOf gives you a read-only List whereas arrayListOf gives you a MutableList. It's definitely preferred to use read-only data structures whenever possible.

val l1 = listOf(1)
l1.add(2) //not possible

val l2 = arrayListOf(2)
l2.add(1) //ok

On the other hand, if you don't fully rely on type inference, you can make the variable for the ArrayList read-only as well:

val l3: List<Int> = arrayListOf(2)
l3.add(1) //not possible anymore

The point of not using arrayListOf is that you want to rely on the library to choose the actual implementation. As of now this happens to be an ArrayList which could change in future releases. For instance, if Kotlin decides to add a more powerful backward-compatible version of an ArrayList, they could change the implementation and your code would keep working (in an improved way). If you, on the other hand, want to rely on ArrayList (via arrayListOf), you probably have a concrete scenario were only this implementation is acceptable.

like image 135
s1m0nw1 Avatar answered Jan 07 '23 10:01

s1m0nw1