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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With