How to create list in Kotlin?

From the Kotlin documentation on Collections:

Kotlin does not have dedicated syntax constructs for creating lists or sets. Use methods from the standard library, such as listOf(), mutableListOf(), setOf(), mutableSetOf().

There are no list literals currently for code outside of annotations.


So for the case of mutable lists, you can declare an empty String one with: val list: MutableList<String> = mutableListOf(). If you wanted an immutable list then you could use val like so: val list: List<String> = listOf("x", "y", "z").

Also note, that you should consider your use case for using val or var. Mutability of a list pertains to values within the list itself, where as val and var are for the variable. You can reassign the list if you use var but not val (similar to final of Java)

For the sake of clarity, as an example, mutable lists can have elements added an removed after their initialisation, while immutable cannot.

Immutable Lists Docs

Mutable List Docs


As @Carcigenicate pointed out, there is not syntax for [null, null].
However, Kotlin does have some handy methods for handling lists and arrays.

Lists

  • listOf()

    Creates a new read-only List.

  • listOfNotNull()

    Basically the same as listOf(), but without null values. Even empty strings are skipped.

  • arrayListOf()

    Creates an ArrayList. This time you can modify (add/remove) elements.

  • mutableListOf()

    Behaves like arrayListOf(). Actually, mutableListOf() internally uses ArrayLists. Read more

Arrays

  • arrayOf()

    This creates an array, which is very different to most languages you know. Instead of syntax structures like {1, 2, 3} or [1, 2, 3] you have functions in Kotlin. You also get functions for typed array:

    • booleanArrayOf()
    • doubleArrayOf()
    • charArrayOf()
    • ...

One exception are annotations, which explains your compiler error [Collection literals outside of annotations]:

@MyAnnotation(arguments = [1, 2, 3])

However, this could change in the future as discussed here.


While working with arrays, it is important to know the return types those functions are creating. As an example: Array<Int> is an Integer[] under the hood, while IntArray is a primitive int[] when targeting the JVM.

Tags:

Kotlin