[kotlin] How do I initialize Kotlin's MutableList to empty MutableList?

Seems so simple, but, how do I initialize Kotlin's MutableList to empty MutableList?

I could hack it this way, but I'm sure there is something easier available:

var pusta: List<Kolory> = emptyList()
var cos: MutableList<Kolory> = pusta.toArrayList()

This question is related to kotlin

The answer is


I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

Various forms depending on type of List, for Array List:

val myList = mutableListOf<Kolory>() 
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()

For LinkedList:

val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()

For other list types, will be assumed Mutable if you construct them directly:

val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()

This holds true for anything implementing the List interface (i.e. other collections libraries).

No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:

val myList: List<Kolory> = ArrayList()