How to initialize List<T> in Kotlin?
Solution 1:
listOf
top-level function to the rescue:
val geeks = listOf("Fowler", "Beck", "Evans")
Solution 2:
Both the upvoted answers by Ilya and gmariotti are good and correct. Some alternatives are however spread out in comments, and some are not mentioned at all.
This answer includes a summary of the already given ones, along with clarifications and a couple of other alternatives.
Immutable lists (List
)
Immutable, or read-only lists, are lists which cannot have elements added or removed.
- As Ilya points out,
listOf()
often does what you want. This creates an immutable list, similar toArrays.asList
in Java. - As frogcoder states in a comment,
emptyList()
does the same, but naturally returns an empty list. -
listOfNotNull()
returns an immutable list excluding allnull
elements.
Mutable lists (MutableList
)
Mutable lists can have elements added or removed.
- gmariotti suggests using
mutableListOf()
, which typically is what you want when you need to add or remove elements from the list. -
Greg T gives the alternative,
arrayListOf()
. This creates a mutableArrayList
. In case you really want anArrayList
implementation, use this overmutableListOf()
. - For other
List
implementations, which have not got any convenience functions, they can be initialized as, for example,val list = LinkedList<String>()
. That is simply create the object by calling its constructor. Use this only if you really want, for example, aLinkedList
implementation.
Solution 3:
Just for adding more info, Kotlin offers both immutable List
and MutableList
that can be initialized with listOf
and mutableListOf
. If you're more interested in what Kotlin offers regarding Collections, you can go to the official reference docs at Collections.