124

I see Kotlin has a List<out E> collection and I was wondering about different ways to initialize one. In Java, I could write:

List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");

How can I achieve the same in Kotlin?

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • 11
    With [`listOf`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html) ? – Michael Apr 27 '16 at 17:30

7 Answers7

187

listOf top-level function to the rescue:

val geeks = listOf("Fowler", "Beck", "Evans")
Ilya
  • 21,871
  • 8
  • 73
  • 92
  • 14
    Calling [listOf](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html) without any parameter gets you an empty list, or just call [emptyList](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/empty-list.html) to make it more readable. – frogcoder Jun 14 '16 at 14:50
  • 4
    There's also [arrayListOf](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/array-list-of.html) – Greg T Oct 08 '17 at 22:06
  • 1
    Is it mutable for later modification? – IgorGanapolsky Feb 19 '20 at 14:42
  • 2
    @IgorGanapolsky The returned type is a read-only `List`, so one shouldn't assume that it is mutable. – Ilya Feb 19 '20 at 15:51
31

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 to Arrays.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 all null 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 mutable ArrayList. In case you really want an ArrayList implementation, use this over mutableListOf().
  • 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, a LinkedList implementation.
Magnilex
  • 11,584
  • 9
  • 62
  • 84
  • 1
    Just an addition: I need often a mutable list with a generic type parameter. `val mutableList = mutableListOf()`with `` or another class as type parameter. – Hermann Schwarz Sep 20 '21 at 05:30
17

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.

gmariotti
  • 479
  • 4
  • 14
10

Let me explain some use-cases : let's create an immutable(non changeable) list with initializing items :

val myList = listOf("one" , "two" , "three")

let's create a Mutable (changeable) list with initializing fields :

val myList = mutableListOf("one" , "two" , "three")

Let's declare an immutable(non changeable) and then instantiate it :

lateinit var myList : List<String>
// and then in the code :
myList = listOf("one" , "two" , "three")

And finally add some extra items to each :

val myList = listOf("one" , "two" , "three")
myList.add() //Unresolved reference : add, no add method here as it is non mutable 

val myMutableList = mutableListOf("one" , "two" , "three")
myMutableList.add("four") // it's ok 
CodeRanger
  • 370
  • 3
  • 12
6

In this way, you can initialize the List in Kotlin

val alphabates : List<String> = listOf("a", "b", "c")
Nikhil Katekhaye
  • 2,344
  • 1
  • 18
  • 19
2

There is one more way to build a list in Kotlin that is as of this writing in the experimental state but hopefully should change soon.

inline fun <E> buildList(builderAction: MutableList<E>.() -> Unit): List<E>

Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements.

Example:

val list = buildList {
    testDataGenerator.fromJson("/src/test/resources/data.json").forEach {
        add(dao.insert(it))
    }
}

For further reading check the official doc.

pgiecek
  • 7,970
  • 4
  • 39
  • 47
1

If you want to initialize without type:

var temp: ArrayList<String> = ArrayList()
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37